Linux进程编程实例详解

我们都知道Linux是一个多任务的系统,它可以支持高并发执行任务。可以通过pstree命令查看树状的进程图。

在这里插入图片描述

代码1

#include <stdio.h>
#include <unistd.h>  //这个包里面有getpid和getppid

int main()
{
    
    
    printf("系统分配的进程号pid:%d\n", getpid());
    printf("系统分配的父进程号ppid:%d\n", getppid());
    return 0;
}

结果表明的执行时系统为程序分配了进程,且有独立唯一的进程号。

在这里插入图片描述

代码2

#include <stdio.h>
#include <unistd.h>

int main()
{
    
    
    char *args[] = {
    
    "/usr/bin/vim", NULL};
    printf("系统分配的进程号pid:%d\n", getpid());
    if (execve("/usr/bin/vim", args, NULL))      
        //execve创建进程,执行/usr/bin/vim 
        perror("用execvve创建进程出错");
    return 1;
}

结果正确,直接执行vim的可执行程序

在这里插入图片描述

代码3

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
    
    
    int newret;
    printf("系统分配的进程号pid:%d\n", getpid());
    newret = system("ping www.baodu.com");  
    //system调用程序
    return 0;
}

结果直接调用ping

在这里插入图片描述

代码4

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>

int main()
{
    
    
    pid_t result;
    result = fork();  //调用fork函数
    int newret;
    if (result == -1)    //-1表示失败
    {
    
    
        perror("创建子进程失败");
        exit;   //exit退出
    }
    else if (result == 0)   //0 表示时子进程
    {
    
    
        printf("返回值是:%d,说明这是子进程!\n此进程的进程号pid:%d\n此进程的父进程号ppid:%d\n", result, getpid(), getppid());
        newret = system("ls -l");    //输出ls -l
    }
    else    //此时是父进程
    {
    
    
        sleep(10);    //sleep 10 秒
        printf("返回值是:%d,说明这是父进程!\n此进程的进程号pid:%d\n此进程的父进程号ppid:%d\n", result, getpid(), getppid());
        newret = system("ping www.baidu.com");   //调用ping
    }
}

可以看到调用了ping,说明是父进程

在这里插入图片描述

代码5

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main()
{
    
    
    pid_t result;
    result = fork();
    // int newret;
    if (result == -1)  
    {
    
    
        perror("创建子进程失败");
        exit(0);
    }
    else if (result == 0)
    {
    
    
        printf("测试中止进程的_exit函数!\n");
        printf("这一行用缓存");  
        _exit(0);
    }
    else
    {
    
    
        printf("测试中止进程的exit函数!\n");
        printf("这一行用缓存");
        exit(0);
    }
}

使用_exit()

在这里插入图片描述

总结

本次文章学习研究了linux的进程。

猜你喜欢

转载自blog.csdn.net/weixin_44617651/article/details/129808716