Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

exec

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", "/bin/ping" , "-c", "1", "-t", "1", ip_addr, NULL);

How can i get returned value of ping command to find out if it returned 0 or 1?

like image 934
skujins Avatar asked Apr 19 '10 11:04

skujins


People also ask

What does the exec () family of system calls do?

The exec family of system calls replaces the program executed by a process. When a process calls exec, all code (text) and data in the process is lost and replaced with the executable of the new program.

What does exec () do in C?

The exec family of functions replaces the current running process with a new process. It can be used to run a C program by using another C program. It comes under the header file unistd.

What are the parameters of the exec () system call?

In execl() system function takes the path of the executable binary file (i.e. /bin/ls) as the first and second argument. Then, the arguments (i.e. -lh, /home) that you want to pass to the executable followed by NULL. Then execl() system function runs the command and prints the output.

What are the differences among the family of exec () functions?

exec() family of functions replaces existing process image with a new process image. This is a marked difference from fork() system call where the parent and child processes co-exist in the memory.


1 Answers

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 <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
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;
}
like image 184
Khaled Alshaya Avatar answered Oct 01 '22 12:10

Khaled Alshaya