tags:

views:

354

answers:

4

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?

+2  A: 

exec function familly does not return, the return int is here only when an error occurs at launch time (like not finding file to exec).

You have to catch return value from the signal sent to the process that forked before calling exec.

call wait() or waitpid() in your signal handler (well, you can also call wait() in your process without using any signal handler if it has nothing else to do).

kriss
A: 

You can wait on the child process and get its exit status. The system call is wait(pid), try to read about it.

duduamar
+4  A: 

You can use waitpid to get the exit status of you child process as:

int childExitStatus;
waitpid( pID, &childExitStatus, 0); // where pID is the process ID of the child.
codaddict
A: 

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;
}
AraK
but in this example i will get exit(number); value returned in WEXITSTATUS(statval). How can i detect returned value of ping command?
Skuja
Instead of exit(number) write your exec.
Let_Me_Be
but execl() doesnt return any value, execpt if it fails, therefore ping command returns 0 or 1
Skuja
AraK
yes, finally i understand this,thanks again.
Skuja