Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ linux中system()函数如何实现waitpid()函数_C++_C_Linux - Fatal编程技术网

C++ linux中system()函数如何实现waitpid()函数

C++ linux中system()函数如何实现waitpid()函数,c++,c,linux,C++,C,Linux,我读了Richard Stevens的“UNIX环境中的高级编程”,找到了这个主题 *8.13。系统功能 *****因为系统是通过调用fork、exec和waitpid实现的,所以有三种类型的返回值** 1。如果fork失败或waitpid返回EINTR以外的错误,系统将返回–1并设置errno以指示错误。 2。如果exec失败,意味着shell无法执行,那么返回值就好像shell已经执行了exit(127)。 **三,。否则,所有三个函数fork、exec和waitpid都会成功,系统返回的值

我读了Richard Stevens的“UNIX环境中的高级编程”,找到了这个主题

*8.13。系统功能

*****因为系统是通过调用fork、exec和waitpid实现的,所以有三种类型的返回值**

1。如果fork失败或waitpid返回EINTR以外的错误,系统将返回–1并设置errno以指示错误。

2。如果exec失败,意味着shell无法执行,那么返回值就好像shell已经执行了exit(127)。

**三,。否则,所有三个函数fork、exec和waitpid都会成功,系统返回的值是shell的终止状态,格式为waitpid******

据我所知,我们fork()使用cmdstring名称的进程和exec()使其与父进程分离

但是无法确定waitpid()函数如何成为system()函数调用的一部分

下面的链接没有为我提供正确的答案。

关闭
fork()
后,原始过程立即继续,即
fork()
立即返回。此时,新流程仍在运行。由于
system()
应该是同步的,即只有在执行的程序完成后才能返回,因此原始程序现在需要在新进程的PID上调用
waitpid()
,以等待其终止

在图片中:

   [main process]
         .
         .
         .
       fork()     [new process]
         A
        / \
       |   \
       |    \___  exec()
  waitpid()         .
      z             .
      z             . (running)
      z             .
      z           Done!
      z             |
      +----<----<---+
      |
      V
  (continue)
[主进程]
.
.
.
fork()[新进程]
A.
/ \
|   \
|\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
waitpid()。
Z
Z(正在运行)
Z
完成了!
z|
+---- 从手册页:

system()通过调用/bin/sh-c命令执行命令中指定的命令,并在命令完成后返回。在命令执行期间,SIGCHLD将被阻止,SIGINT和SIGQUIT将被忽略

system()可能使用
waitpid()
等待shell命令完成。

在Unix环境中,
system()
调用如下:

int system(const char *cmd)
{
   int pid = fork();
   if(!pid)  // We are in the child process. 
   {
       // Ok, so it's more complicated than this, it makes a new string with a
       // shell in it, etc. 
       exec(cmd);
       exit(127);  // exec failed, return 127. [exec doesn't return unless it failed!]
   }
   else
   {
       if (pid < 0)
       {
            return -1;   // Failed to fork!
       }
       int status;
       if (waitpid(pid, &status, 0) > 0)
       {
           return status;
       }
   }
   return -1;
}
int系统(常量字符*cmd)
{
int-pid=fork();
if(!pid)//我们在子进程中。
{
//好的,所以它比这更复杂,它用
//壳在里面等。
行政主任(cmd);
退出(127);//exec失败,返回127。[除非失败,否则exec不会返回!]
}
其他的
{
if(pid<0)
{
return-1;//分叉失败!
}
智力状态;
if(waitpid(pid和status,0)>0)
{
返回状态;
}
}
返回-1;
}
请注意,这是
系统
所做的象征性工作-它相当复杂,因为
waitpid
可以给出其他值,以及所有需要检查的其他内容