简体   繁体   English

ps命令linux vs Unix在c程序中的不同行为

[英]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 | 我有一个简单的c程序,执行“ ps”并将其通过管道传递给“ grep”,基本上是“ ps | grep x'. 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. 我的问题是,当我在UNIX(Solaris)上运行此程序时,它是完美的,但是当我在(Debian)上运行此程序时,它可以正确执行,但给我一条错误消息。

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. 我尝试了同一程序运行不同的命令,例如“ ls”和“ grep”,但在任一操作系统上都没有问题。 What makes 'ps' different? 是什么使“ ps”与众不同?

EDIT: 编辑:
added the included libraries to the code. 在代码中添加了包含的库。

When your program calls fork, it creates a parent process and a child process. 当您的程序调用fork时,它将创建一个父进程和一个子进程。 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. 在子进程fork中返回0,在父进程fork中返回1。无论何时子进程终止,SIGCHLD信号都会发送到父进程。

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. 现在,在您的情况下,您在父execlp和子execlp中都调用execlp ,它将替换正在运行的进程映像,但不会更改关系。 This means that ps is your parent process and grep is your child process. 这意味着ps是您的父进程, grep是您的子进程。 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. 通常这并不重要,因为默认情况下程序会忽略SIGCHLD,但是ps捕获所有未知信号并使用您在此处看到的消息退出。 You can see the relevant function in the source code for ps (or rather procps ). 您可以在ps (或procps )的源代码中看到相关功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM