Lex
Lex

Reputation: 396

ps command linux vs unix different behavior in c program

I have a simple c program that executes 'ps' and pipes it to 'grep', basically 'ps | grep x'.

the code goes more or less something like this:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(){
    int pipefd[2];
    int pid;

    pipe(pipefd);
    pid=fork();

    if (pid == 0){
        close(pipefd[1]);
        dup2(pipefd[0], 0);
        close(pipefd[0]);
        execlp("grep", "grep", "b", (char *) 0);
    }
    else{
        close(pipefd[0]);
        dup2(pipefd[1], 1);
        close(pipefd[1]);
        execlp("ps", "ps", (char *) 0);
    }
    exit(0);
}

The problem that i have is that when i run this on unix (Solaris) is works perfect, but when i run this on (Debian) it executes properly but gives me an error message.

error message:

Signal 17 (CHLD) caught by ps (procps-ng version 3.3.3).
ps:display.c:59: please report this bug

I have try the same program running different commands like 'ls' and 'grep' with no problem on either os. What makes 'ps' different?

EDIT:
added the included libraries to the code.

Upvotes: 1

Views: 1061

Answers (1)

Mike Pelley
Mike Pelley

Reputation: 3116

When your program calls fork, it creates a parent process and a child process. In the child process fork returns 0 and in the parent it returns 1. Whenever a child process terminates, a SIGCHLD signal is sent to the parent process.

Now, in your case you call execlp in both the parent and child process, which replaces the running process image but does not change the relationship. This means that ps is your parent process and grep is your child process. Normally this would not matter, as programs ignore SIGCHLD by default, but ps catches all unknown signals and quits with the message you see there. You can see the relevant function in the source code for ps (or rather procps).

Upvotes: 2

Related Questions