• Linux学习-1进程


    在Linux中,在一个程序的内部启动另外一个程序,从而创建一个新进程。

    1.这个工作可以通过库函数system来完成。

    #include<stdlib.h>

    int system (const char *string);

    system函数的作用是,运行以字符串参数形式的传递给他打命令并等待该命令完成。命令的执行情况就如同在shell中执行如下的命令:

    $ sh -c string

    如果无法启动shell来运行这个命令,system函数将返回错误码127,其他错误返回-1.

    system.c

    #include<stdlib.h>
    #include<stdio.h>
    int main()
    {
        printf("Running upper with system
    ");
        system("./upper");
        printf("Done.
    ");
        exit(0);
    
    }

    编译gcc system.c -o system

    执行时./system

    此时会发现会执行upper程序。

    2.创建进程底层接口exec。

    exec系列函数由一组相关的函数组成,他们在进程的启动方式和程序参数的表达方式上各有不同。exec函数可以把当前进程替换为一个新进程。你可以使用exec函数将程序的执行从一个程序切换到另一个程序。

    exec函数比system函数更有效,因为在新的程序启动后,原来的程序就不再运行了。

    #include<unistd.h>

    int execl(xxx);

    int execlp(xxx);

    int execle(xxx);

    int execv(xxx);

    int execvp(xxx);

    int execve(xxx);                        

    还是以upper程序为例:

    exe_up.c    

    #include<stdio.h>
    #include<unistd.h>
    #include<stdlib.h>
    int main()
    {
        printf("runing with execlp
    ");
        execlp("./upper", "/upper", NULL);
        printf("down");
        exit(0);
    }

     gcc exe_up.c -o exe_up

    ./exe_up

    ps:

    upper.c

    #include<stdio.h>
    #include<stdlib.h>
    #include<ctype.h>
    int main()
    {
        int ch;
        while( EOF != (ch=getchar()))
        {
            putchar(toupper(ch));
        }
        exit(0);    
    
    }

    gcc upper.c -o upper

     以上所有内容来自《Linux程序设计 第四版》

  • 相关阅读:
    分布式设计与开发(一)------宏观概述
    分布式设计与开发(二)------几种必须了解的分布式算法
    分布式设计与开发(三)------高一致性服务ZooKeeper
    jvm工作原理
    JVM原理和优化
    分布式系统设计原理与方案
    在Linux上安装Memcached服务
    使用Memcached、Spring AOP构建数据库前端缓存框架
    Java使用memcached
    Memcache的部署和使用
  • 原文地址:https://www.cnblogs.com/xiaodeyao/p/6390553.html
Copyright © 2020-2023  润新知