进程创建system、exec、fork

进程是操作系统进行资源分配和调度的基本单位。
进程号: 进程号可以通过getpid获取, 父进程号可以通过getppid获取。

通过system库函数创建进程

system的原型如下, 其作用是运行以字符串参数的形式传递给它的命令并等待该命令的完成。其作用等价于在shell中执行命令sh -c string。

#include <stdlib.h>

int system(const char *string);
#include <stdlib.h>
#include <stdio.h>

int main()
{
    printf("running cat with system.\n");
    system("cat system1.c");
    printf("-----------\nDone.\n");
    return 0;
}

其运行结果与sh -c “cat system1.c”类似。

通过exec系列函数创建进程

exec函数可以把当前进程替换为一个新的进程, 新的进程由path或则file参数指定。 切换到新的进程以后,原来的进程就不再运行了。
函数原型如下:

#include <unistd.h>

char **environ;

int execl(const char *path, const char *arg0, ..., (char*)0);
int execlp(const char *file, const char *arg0, ..., (char*)0);
int execle(const char *path, const char *arg0, ..., (char*)0, char *const envp[]);

int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execve(const char *file, char *const argv[], char *const envp[]);

前三个函数参数是可变的, 后面三个函数接收字符串数组。

全局变量environ用来把一个值传递到新的程序环境中。

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

int main()
{
    printf("Running ps with execlp.\n");
    execlp("ps", "ps", "ax", 0);
    printf("Done.\n");

    return 0;
}

编译执行后,看不到printf输出Done, 原因就是最初的进程被替换了。

通过fork创建进程

fork函数复制当前线程, 父进程的内存数据会原封不动的拷贝到子进程中, 在进程表中创建一个新的表项, 新表项中的许多属性与当前进程是相同的, 但是新进程有自己的数据空间,环境和文件描述符。

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

pid_t fork(void);

父进程中fork调用返回的是新的子进程的pid, 子进程中的fork调用返回的是0。可以利用这个来判断父子进程。 fork失败将返回-1。

想要弄明白fork函数, 只需要弄懂下面几个程序即可,具体解释可以看下面几个相关博客
程序1:

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

int main()
{
    pid_t pid1;
    pid_t pid2;

    pid1 = fork();
    pid2 = fork();

    printf("pid1: %d, pid2: %d\n", pid1, pid2);
    return 0;
}

输出:

$ ./test_fork
pid1: 18585, pid2: 18586
pid1: 18585, pid2: 0
pid1: 0, pid2: 18587
pid1: 0, pid2: 0

程序2:

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

int main()
{
    int res = fork() && fork() || fork();
    printf("%d 's result is %d.\n", getpid(), res);

    return 0;
}

输出:

$ ./test_fork2
18645 's result is 1.
18647 's result is 1.
18648 's result is 0.
18646 's result is 1.
18649 's result is 0.

程序3:

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

int main()
{
    int i;
    for (i = 0; i < 2; i++)
    {
        fork();
        printf("-");
    }
    wait(NULL);
    wait(NULL);

    return 0;
}

输出:

$ ./test_fork3
--------

相关博客

一个fork的面试题
从一道面试题谈linux下fork的运行机制
一个FORK的面试题
多线程与fork
论fork()函数与Linux中的多线程编程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值