linux进程篇 (二) 进程的基本控制

2. 进程的基本操做

接口函数函数

#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;
}
相关文章
相关标签/搜索