linux进程篇 (二) 进程的基本控制
生活随笔
收集整理的這篇文章主要介紹了
linux进程篇 (二) 进程的基本控制
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
接口函數(shù)
#include <unistd.h> //創(chuàng)建子進(jìn)程 pid_t fork(void);//結(jié)束子進(jìn)程 void exit(int status);//進(jìn)程等待 #include <sys/wait.h> pid_t wait(int *stat_loc);//進(jìn)程睡眠 unsigned int sleep(unsigned int seconds);?
2.1 創(chuàng)建子進(jìn)程
//創(chuàng)建子進(jìn)程 //pid_t 用于保存PID信息的結(jié)構(gòu)體,如果創(chuàng)建子進(jìn)程成功,返回子進(jìn)程PID, //如果pid == 0 表示子進(jìn)程 pid_t fork(void);?
2.2 取消進(jìn)程
void exit(int status); //exit 用于結(jié)束子進(jìn)程,使用還函數(shù)會釋放子進(jìn)程的所有占用資源,status 數(shù)值用于返回給父線程?
2.3 同步進(jìn)程
pid_t wait(int *stat_loc); //wait 用于父進(jìn)程和子進(jìn)程同步,父進(jìn)程調(diào)用后,就進(jìn)入睡眠狀態(tài),直到子進(jìn)程結(jié)束或者被其他事件喚醒。?
例子:創(chuàng)建子進(jìn)程,打印父子進(jìn)程的pid
#include <sys/types.h> //提供系統(tǒng)調(diào)用標(biāo)志 #include <sys/stat.h> //提供系統(tǒng)狀態(tài)信息和相關(guān)函數(shù) #include <sys/uio.h> //提供進(jìn)程I/O操作函數(shù) #include <unistd.h> //標(biāo)準(zhǔn)函數(shù)庫 #include <fcntl.h> //文件操作相關(guān)函數(shù)庫 #include <string.h> //字符串操作函數(shù)庫 #include <sys/wait.h> //wait調(diào)用相關(guān)函數(shù)庫 #include <stdio.h> //標(biāo)準(zhǔn)輸入輸出函數(shù)庫 #include <stdlib.h> //常用工具函數(shù)庫int main(int argc, char const *argv[]) {int fd;pid_t pid;char buf[1024] = {0}; //緩沖空間int status;const char *s1="我是子進(jìn)程";fd = open("file",O_RDWR | O_CREAT, 0755);if(fd < 0){perror("open");return -1;}strcpy(buf,"我是父進(jìn)程");pid = fork();if(pid == 0){//子進(jìn)程strcpy(buf,"我是子進(jìn)程");puts("我是子進(jìn)程");printf("子進(jìn)程的pid為 %d\n",getpid());printf("父進(jìn)程的pid為 %d\n",getppid());write(fd,buf,strlen(buf));close(fd);exit(status);}else if(pid > 0){//父進(jìn)程puts("我是父進(jìn)程");printf("父進(jìn)程的pid是 %d\n",getpid());printf("子進(jìn)程的pid是 %d\n",pid);write(fd,buf,strlen(buf));close(fd);}else{perror("fork");close(fd);return -1;}wait(&status);return 0; }?
轉(zhuǎn)載于:https://www.cnblogs.com/kmist/p/10634224.html
總結(jié)
以上是生活随笔為你收集整理的linux进程篇 (二) 进程的基本控制的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 云笔记项目-Spring事务学习-传播M
- 下一篇: 别人的Linux私房菜(17)进程管理与