简体   繁体   中英

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...

The system-call functions we use on these cases are, 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?.

Demonstration:

Open your console and write nano program.c , paste the following code. theng compile it with gcc program.c -o program and you will get the 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> .

open() , read() , fork() , pipe() etc. are Posix system calls, not covered by the C Standard. Posix specifies that most of them should be declared in <unistd.h> (though open() comes from <fcntl.h> instead).

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; C99 and C11 do not. Your sample code will compile with an accommodating compiler and produce correct output because the system calls used have very basic APIs. Compiling the same code with -Wall -Werror -std=c99 should fail to produce an executable.

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. People on Stack Overflow insist on writing correct code most of the time, hence the inclusion of the correct headers.

Because those functions are declared in different header files.

Eg exit() is declared in stdlib.h , pipe() is declared in unistd.h

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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