【问题标题】:why pid of child and its process are different?为什么孩子的pid及其过程不同?
【发布时间】:2014-04-03 05:07:03
【问题描述】:

这是我的代码:

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 %d\n", WIFEXITED(stat_val));
    else
    printf("Child has existed abnormally\n");
    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.cshPIDPID 处得到不同的 PID 孩子。谁能帮帮我。我想得到我的process setup.csh 中的PID

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

【问题讨论】:

  • 这不清楚。您在LINE_1 上看到一个值;您看到的其他价值是什么?
  • @OliCharlesworth 使用 ps -u | grep setup.csh 我已经更新了我的问题。

标签: c++ process pid


【解决方案1】:

当你运行时:

sh -c 'setup.csh &'

原来的 shell 进程派生出另一个子进程来运行csh。流程层次结构是:

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

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

实际上,有一种方法可以实现这一点。如果您使用exec shell 命令,它会在自己的进程中运行指定的命令,而不是派生一个子进程:

system1('exec setup.csh &');

【讨论】:

  • 有什么办法可以得到进程 setup.csh 的PID 并且如果使用system() 运行,那么我也不会得到 PID。
  • 不,您也无法使用system() 获得它。它的工作方式与您的 system1() 函数几乎相同。 setup.csh是孙进程,只能直接访问子进程。
  • 不,你不能那样做。 execl 不处理命令中的 shell 语法。它不会拆分参数,它不理解&amp;等。
  • @Balmar 正如你所说运行system1('exec setup.csh &amp;') 那么我应该如何处理命令传递给system1
  • 这适用于您现有的 system1 定义。
猜你喜欢
  • 2014-11-18
  • 1970-01-01
  • 1970-01-01
  • 2016-02-29
  • 1970-01-01
  • 2021-07-24
  • 1970-01-01
  • 2018-07-02
  • 1970-01-01
相关资源
最近更新 更多