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 取消进程

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
",getpid());
        printf("父进程的pid为 %d
",getppid());

        write(fd,buf,strlen(buf));
        close(fd);
        exit(status);

    }else if(pid > 0)
    {
        //父进程
        puts("我是父进程");
        printf("父进程的pid是 %d
",getpid());
        printf("子进程的pid是 %d
",pid);

        write(fd,buf,strlen(buf));
        close(fd);


    }
    else{
        perror("fork");
        close(fd);
        return -1;
    }
    wait(&status);
    return 0;
}