进程综合测试案例

实现目标

1、创建3个子进程。
2、子进程1执行pwd的命令,子进程2执行当前目录下的额一个段错误的ELF文件,子进程3执行ps命令。
3、使用execl、execlp等函数实现。

测试源码

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

int main(int argc, const char* argv[])
{
    int i = 0;
    int number = 3;
    pid_t pid;

    for(i = 0; i<number; ++i)
    {
        pid = fork();
        if(pid == 0)
        {
            break;
        }
    }

    // 父进程
    if(i == number)
    {
        sleep(2);
        // 回收子进程
        pid_t wpid;
        int status;
        while( (wpid = waitpid(0, &status, WNOHANG)) != -1 )
        {
            if(wpid == 0)
            {
                continue;
            }
            printf("child pid = %d\n", wpid);
            if(WIFEXITED(status))
            {
                printf("return number: %d\n", WEXITSTATUS(status));
            }
            else if(WIFSIGNALED(status))
            {
                printf("exit by signal: %d\n", WTERMSIG(status));
            }
        }
    }
    else if(i == 0)
    {
        execl("/bin/pwd", "pwd", NULL);
    }
    else if(i == 1)
    {
        execl("./error", "error", NULL);
    }
    else if(i == 2)
    {
        execlp("ps", "ps", "aux", NULL);
    }

    printf("over......\n");
    return 0;
}

生成段错误的文件的源码

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


int main(int argc, const char* argv[])
{
    char* p = "hello, world......";

    p[2] = '9';
    printf("%s\n", p);

    return 0;
}

测试结果

子进程1执行结果

子进程2执行结果

在这里插入图片描述

子进程3执行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/zxy131072/article/details/89493146