接口函數函數
#include <unistd.h> //建立子進程 pid_t fork(void); //結束子進程 void exit(int status); //進程等待 #include <sys/wait.h> pid_t wait(int *stat_loc); //進程睡眠 unsigned int sleep(unsigned int seconds);
2.1 建立子進程工具
//建立子進程 //pid_t 用於保存PID信息的結構體,若是建立子進程成功,返回子進程PID, //若是pid == 0 表示子進程 pid_t fork(void);
2.2 取消進程ui
void exit(int status); //exit 用於結束子進程,使用還函數會釋放子進程的全部佔用資源,status 數值用於返回給父線程
2.3 同步進程spa
pid_t wait(int *stat_loc); //wait 用於父進程和子進程同步,父進程調用後,就進入睡眠狀態,直到子進程結束或者被其餘事件喚醒。
例子:建立子進程,打印父子進程的pid線程
#include <sys/types.h> //提供系統調用標誌 #include <sys/stat.h> //提供系統狀態信息和相關函數 #include <sys/uio.h> //提供進程I/O操做函數 #include <unistd.h> //標準函數庫 #include <fcntl.h> //文件操做相關函數庫 #include <string.h> //字符串操做函數庫 #include <sys/wait.h> //wait調用相關函數庫 #include <stdio.h> //標準輸入輸出函數庫 #include <stdlib.h> //經常使用工具函數庫 int main(int argc, char const *argv[]) { int fd; pid_t pid; char buf[1024] = {0}; //緩衝空間 int status; const char *s1="我是子進程"; fd = open("file",O_RDWR | O_CREAT, 0755); if(fd < 0) { perror("open"); return -1; } strcpy(buf,"我是父進程"); pid = fork(); if(pid == 0) { //子進程 strcpy(buf,"我是子進程"); puts("我是子進程"); printf("子進程的pid爲 %d\n",getpid()); printf("父進程的pid爲 %d\n",getppid()); write(fd,buf,strlen(buf)); close(fd); exit(status); }else if(pid > 0) { //父進程 puts("我是父進程"); printf("父進程的pid是 %d\n",getpid()); printf("子進程的pid是 %d\n",pid); write(fd,buf,strlen(buf)); close(fd); } else{ perror("fork"); close(fd); return -1; } wait(&status); return 0; }