为什么孩子的PID及其过程不同

why pid of child and its process are different?

本文关键字:过程 孩子 PID 为什么      更新时间:2023-10-16

这是我的代码:

extern int errno;
pid_t system1(const char * command)
{
    pid_t pid;
    pid = fork();
    cout<<"PID in child "<<(int)pid<<endl;
    if (pid < 0) {
        return pid;
    } else if (pid == 0) {
        execl("/bin/sh", "sh", "-c", command, (char*)NULL);
        _exit(1);
    }
    int stat_val;
    pid_t child_pid;
    cout << "Hello1" << endl;
    child_pid = wait(&stat_val);
    cout << "child_pid = " <<(int)child_pid<< endl;//LINE 1
    if(WIFEXITED(stat_val))
    printf("Child has terminated with exit code %dn", WIFEXITED(stat_val));
    else
    printf("Child has existed abnormallyn");
    return child_pid;
}
int main( )
{ 
    int pid_1 = system1("setup.csh &");;
    struct stat status;
    sleep(10);
    cout<<"errno  = "<<errno<<endl;
    int i = kill(pid_1,0);
    cout<<"Pid id = "<<pid_1<<endl;
    cout<<"i === "<<i<<endl;
    cout<<"errno  = "<<errno<<endl;
    if(errno == ESRCH)
    {
        cout<<"process does not exist";
    }
    else
    {
        cout<<"process exist"<<endl;
    }
    return 0;
}

在上面的代码中,我在LINE 1process setup.csh PID得到了不同的孩子PID。谁能帮帮我。我想得到我的process setup.csh PID

我正在使用控制台中的ps -u user | grep setup.csh寻找其他PID值。

当您运行时:

sh -c 'setup.csh &'

原始 shell 进程派生另一个子进程以运行csh 。流程层次结构为:

YourProgram
    sh -c 'setup.csh &'
        csh setup.csh

没有办法直接在原始程序中获取此PID。为什么不直接从程序中运行setup.csh,而不是通过 shell?

实际上,有一种方法可以做到这一点。如果使用 exec shell 命令,它将在自己的进程中运行指定的命令,而不是分叉子命令:

system1('exec setup.csh &');