我正在为我的小型Web服务器编写一个cgi程序。然后该程序分叉以创建一个子程序。据我所知,父级和它的子级共享相同的文件描述符,所以我希望看到子级的输出,但实际上并没有发生。
cgi程序基本上是这样的:
printf("Content-Type: text/plain;charset=us-asciinn");
printf("parent");
pid=fork();
if(pid==0) printf("child");
wait(null);
我期望的是"父母"one_answers"孩子",但实际上只是"父母"。有人能帮我解释一下吗?感谢任何帮助
您应该仔细检查是否确实正在创建子进程。从这里您应该验证返回的pid不是-1,如果是,请检查errno以获取更多信息:
返回值
Upon successful completion, fork() shall return 0 to the child process and shall return the process ID of the child process to the parent process. Both processes shall continue to execute from the fork() function. Otherwise, -1 shall be returned to the parent process, no child process shall be created, and errno shall be set to indicate the error.
错误
The fork() function shall fail if: [EAGAIN] The system lacked the necessary resources to create another process, or the system-imposed limit on the total number of processes under execution system-wide or by a single user {CHILD_MAX} would be exceeded. The fork() function may fail if: [ENOMEM] Insufficient storage space is available.
如果以上内容没有帮助,如果你能提供更多关于你试图在其上执行此操作的操作系统的信息,那可能会很有用,但我认为这是大多数平台上相当标准的代码。