简体   繁体   English

在Linux中创建子进程时的unistd.h或stdlib.h

[英]The unistd.h or stdlib.h when creating child processes in Linux

I would like to know what are the differences between the headers unistd.h and stdlib.h when it's about creating child processes and establishing communications through pipes... 我想知道在创建子进程和通过管道建立通信时,标头unistd.h和stdlib.h之间有什么区别...

The system-call functions we use on these cases are, read() , write() , wait() , pipe() , fork() , exit() . 在这些情况下,我们使用的系统调用函数为read()write()wait()pipe()fork()exit() And it seems that the library stdlib.h has them too, why all the examples here in stackoverflow or other sites include both headers?. 而且似乎stdlib.h库也包含它们,为什么在stackoverflow或其他站点中的所有示例都包含两个标头?

Demonstration: 示范:

Open your console and write nano program.c , paste the following code. 打开控制台并编写nano program.c ,粘贴以下代码。 theng compile it with gcc program.c -o program and you will get the pid: 然后使用gcc program.c -o program编译它,您将获得pid:

#include <stdio.h>
#include <stdlib.h>

int main()
{
   int pid;
   pid = fork();
   printf("EL pid %i\n", pid);
}

Function exit() is defined in the C Standard and its declaration is specified to belong in <stdlib.h> . 函数exit()在C标准中定义,其声明指定为<stdlib.h>所属。

open() , read() , fork() , pipe() etc. are Posix system calls, not covered by the C Standard. open()read()fork()pipe()等是Posix系统调用,C标准未涵盖。 Posix specifies that most of them should be declared in <unistd.h> (though open() comes from <fcntl.h> instead). Posix指定其中大多数应在<unistd.h>声明(尽管open()来自<fcntl.h> )。

Some older systems used to mix or duplicate these declarations, but modern environments do not any longer, in order to comply with these standards. 一些较旧的系统曾经用来混合或复制这些声明,但是为了符合这些标准,现代环境不再使用。

Note that the original C Standard allowed the compiler to guess unknown functions prototypes; 请注意,原始的C标准允许编译器猜测未知函数的原型。 C99 and C11 do not. C99和C11没有。 Your sample code will compile with an accommodating compiler and produce correct output because the system calls used have very basic APIs. 您的示例代码将使用适当的编译器进行编译,并产生正确的输出,因为所使用的系统调用具有非常基本的API。 Compiling the same code with -Wall -Werror -std=c99 should fail to produce an executable. 使用-Wall -Werror -std=c99编译相同的代码将无法生成可执行文件。

Programming this way is considered sloppy and no longer supported. 这种方式的编程被认为是草率的,不再受支持。 C has enough pitfalls as it is to not condone this kind of style any more. C有足够的陷阱,因为它不再宽容这种样式。 People on Stack Overflow insist on writing correct code most of the time, hence the inclusion of the correct headers. Stack Overflow上的人们大多数时候都坚持编写正确的代码,因此要包含正确的标头。

Because those functions are declared in different header files. 因为这些函数是在不同的头文件中声明的。

Eg exit() is declared in stdlib.h , pipe() is declared in unistd.h 例如exit()在stdlib.h中声明, pipe()在unistd.h中声明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM