linux进程篇 (二) 进程的基本控制
生活随笔
收集整理的這篇文章主要介紹了
linux进程篇 (二) 进程的基本控制
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
接口函數
#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 取消進程
void exit(int status); //exit 用于結束子進程,使用還函數會釋放子進程的所有占用資源,status 數值用于返回給父線程?
2.3 同步進程
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; }?
轉載于:https://www.cnblogs.com/kmist/p/10634224.html
總結
以上是生活随笔為你收集整理的linux进程篇 (二) 进程的基本控制的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 云笔记项目-Spring事务学习-传播M
- 下一篇: Spring Boot 面试,一个问题就