进程控制 Linux C fork() execl() exit() wait()
进程控制实验:
在linux下面使用c语言利用系统调用fork(), execl(), exit(), wait()
fork()用来复制进程
int fork() turns a single process into 2 identical processes, known as the parent and the child. On success, fork() returns 0 to the child process and returns the process ID of the child process to the parent process. On failure, fork() returns -1 to the parent process, sets errno to indicate the error, and no child process is created.
execl()调用外部命令
execl stands for execute and leave which means that a process will get executed and then terminated by execl.
exit()
int exit(int status) - terminates the process which calls this function and returns the exit status value. Both UNIX and C (forked) programs can read the status value.
wait()等待子进程执行结束
int wait (int *status_location) - will force a parent process to wait for a child process to stop or terminate. wait() return the pid of the child or -1 for an error. The exit status of the child is returned to status_location.
#define _GNU_SOURCE#include <stdlib.h>#include <stdio.h>#include <unistd.h>#include <sys/types.h>void main() {//execl("/bin/echo", "echo", "I am in execl", (char*)0);pid_t pid;int status = -10;pid=fork();if(pid==0) {printf("i am in son proc\n");printf("pid = %d\n", getpid());int t = wait(&status);printf("t = %d\n", t);printf("status = %d\n", status);//子进程下面没有子进程,wait返回-1,status也未变化sleep(3);}else {//wait(&status) 返回子进程的pid, status为执行exit(5)的一个值// 当然不为5, WEXITSTATUS(status)返回值为5//sleep(3);// wait()会等待子进程执行结束,然后回过来的执行父进程printf("i am in father proc\n"); int t = wait(&status);printf("t = %d\n", t);printf("status = %d\n", status);printf("WEXITSTATUS(status)=%d\n",WEXITSTATUS(status));}exit(5);}