Question

The following code works like this:

I create a pipe to connect two processes. One process will be the command who, in order to know which users are logged on. The other process will be the command grep, which takes who's command output and looks for "user" into this output. Main program's exit code must be 1 if the user is logged on, and 0 if the user's not logged on. Where do I have to take exit code?

Here's the code:

int fd[2];
pipe(fd);

int pid1,pid2;
pid1 = fork();

if (pid1 != 0) {
    pid2 = fork();
    if(pid2 == 0) {
            close(0); dup(fd[0]); close(fd[0]), close(fd[1]);
            execlp("grep","grep ","user",NULL);
    } else {
            close(fd[0]); close(fd[1]);
    }
} else {
    close(1);
    dup(fd[1]);
    close(fd[0]);
    close(fd[1]);
    execlp("who","who",NULL);
}
Was it helpful?

Solution

exec* calls usually do not return. If they return then only because exec failed to load the new process image. In that case the error is returned in errno.

If you are interested in the exit status of your child process then you have to either install a signal handler for SIGCHLD or wait for your child in the parent and retrieve the exit status that way.

For your own convenience you may want to consider using system instead:

int exit_status = system("who | grep user");

OTHER TIPS

execlp() overwrites the address space with the executable command and runs it. So it will return only if there is some error in executing the command. In this case return value is -1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top