[Linux] C language Linux system programming creation process, linux
1. process ID
Each process is represented by a unique identifier, namely, the process ID (pid). The system ensures that each pid is unique at a certain time.
1.1 allocate process ID
By default, the kernel limits the maximum process ID to 32768. You can set/proc/sys/kernel/pid_max here. In a short time, the kernel will not reuse the allocated ID.
2. Obtain the process id and parent process id.
#include <stdio.h> #include <sys/types.h> #include <unistd.h> int main(){ int pid=getpid(); int ppid=getppid(); printf("pid:%d ppid:%d \n",pid,ppid); }
3. Run the new process
First create a new process fork ()
Execute the exec series system call in the new process
4.exe c series system call
The prototype of the execl () function is int execl (const char * path, const char * arg ,...)
Path is the program path, arg is the list of variable length parameters passed to the specified program, and must end with null.
Const can also be used with pointer variables, which can restrict pointer variables and data pointed to by pointers.
Normally, execl () does not return the result. A successful call will end with a jump to the entry point of the new program, and-1 will be returned if an error occurs.
int ret; ret=execl("/usr/bin/vim","vim","text.txt",NULL); if(ret==1){ printf("execl error"); }
5. fork () system call
You can create a process that is the same as the current process image by calling the fork () system. After the caller returns the result from fork (), it continues to run.
The current process is the parent process, and the created process is a child process.
If fork () is successfully called by the parent process, the pid of the child process is returned.
In the subprocess fork () call, 0 is returned.
# Include <stdio. h> # include <unistd. h> int main () {int pid, ppid; int ret = fork (); if (ret> 0) {pid = getpid (); ppid = getppid (); printf ("I am a parent process, pid = % d, ppid = % d, new child process pid = % d \ n", pid, ppid, ret ); sleep (3); // The parent process cannot be terminated too quickly; otherwise, the ppid of the child process cannot be seen.} else if (ret = 0) {pid = getpid (); ppid = getppid (); printf ("I Am a sub-process, pid = % d, ppid = % d \ n", pid, ppid );} else if (ret =-1) {perror ("fork ");}}
I am a parent process, pid = 13890, ppid = 10038, and the new sub-process pid = 13891
I am a sub-process, pid = 13891, ppid = 13890