Get process ID
# Include <sys/types. h> # include <unistd. h> pid_t getpid (void) // obtain the idpid_t getppid (void) of the current process // obtain the parent process ID
Create a sub-process
# Include <unistd. h> pid_t fork (void) // function: create a sub-process and call it once, but return two times. There are three different return values. in the parent process, fork returns the PID of the newly created child process // 2. in the sub-process, fork returns 0 // 3. if an error occurs, fork returns a negative value. // Note: The data space and stack space of a sub-process created using this function will be copied from the parent process, rather than shared.
# Include <sys/types. h> # include <unistd. h> pid_t vfork (void) // function: create a sub-process
Vfork and forkDifferences:
- Fork:The child process copies the data segment of the parent process.
- Vfork:Child process and parent process share data segments
- Fork:The execution sequence of parent and child processes is unknown.
- Vfork:The child process runs first, and then the parent process runs
Exec function family
Exec replaces the program that calls it with the executed program.
Difference from fork: Fork creates a new process, generates a new PID, exec starts a new program, replaces the original process, so the process PID will not change.
Execl
# Include <unistd. h> int execl (const char * path, const char * arg1 ,...) // parameter description: // path: name of the program to be executed (including the complete path) // arg1-argn: command line parameters required by the program to be executed, including the program name. End with a null pointer
Execlp
# Include <unistd. h> int execlp (const char * path, const char * arg1 ,...) // parameter description: // path: name of the program to be executed (excluding the path, the program will be searched from the path environment variable) // arg1-argn: the command line parameter required by the program to be executed, contains the program name. End with a null pointer
Execv
# Include <unistd. h> int execv (const char * path, char * const argv []) // parameter description: // path: name of the program to be executed (including the complete path) // argv []: array of command line parameters required by the program to be executed
System
# Include <stdlib. h> INT system (const char * string) // function: // call fork to generate a sub-process. The sub-process calls/bin/sh-C string to execute the command represented by the string parameter.
Process waiting
# Include <sys/types. h> # include <sys/Wait. H> pid_t wait (int * Status) // function: blocks the process until a sub-process exits