这是我的代码:
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;
}
在上面的代码中,PID
的{{1}}和LINE 1
PID
process
的孩子不同setup.csh
。任何人都可以帮帮我。我想获得PID
process
的{{1}}。
我在控制台中使用setup.csh
查找其他PID
值。
答案 0 :(得分:0)
当你跑步时:
sh -c 'setup.csh &'
原始shell进程要求另一个子进程运行csh
。流程层次结构为:
YourProgram
sh -c 'setup.csh &'
csh setup.csh
无法直接在原始程序中获取此PID。为什么不直接从您的程序运行setup.csh
,而不是通过shell?
实际上,有一种方法可以实现这一目标。如果使用exec
shell命令,它会在自己的进程中运行指定的命令,而不是分叉子进程:
system1('exec setup.csh &');