How to get the return value of a program ran via calling a member of the exec family of functions?

后端 未结 5 2075
面向向阳花
面向向阳花 2020-11-27 06:45

I know that it is possible to read commands output with a pipe? But what about getting return value ? For example i want to execute:

execl(\"/bin/ping\", \"/         


        
5条回答
  •  Happy的楠姐
    2020-11-27 07:49

    Here is an example I wrote long time ago. Basically, after you fork a child process and you wait its exit status, you check the status using two Macros. WIFEXITED is used to check if the process exited normally, and WEXITSTATUS checks what the returned number is in case it returned normally:

    #include 
    #include 
    #include 
    int main()
    {
        int number, statval;
        printf("%d: I'm the parent !\n", getpid());
        if(fork() == 0)
        {
            number = 10;
            printf("PID %d: exiting with number %d\n", getpid(), number);
            exit(number) ;
        }
        else
        {
            printf("PID %d: waiting for child\n", getpid());
            wait(&statval);
            if(WIFEXITED(statval))
                printf("Child's exit code %d\n", WEXITSTATUS(statval));
            else
                printf("Child did not terminate with exit\n");
        }
        return 0;
    }
    

提交回复
热议问题