• 二十六、Linux 进程与信号---system 函数 和进程状态切换


    26.1 system 函数

    26.1.1 函数说明

    system(执行shell 命令)
    相关函数 fork,execve,waitpid,popen

    1 #include <stdlib.h>
    2 int system(const char * string);
    • 函数功能:简化 exec 函数
    • 函数说明
      • system()会调用 fork() 产生子进程,由子进程来调用 /bin/sh -c string 来执行参数 string 字符串所代表的命令,此命令执行完后随即返回原调用的进程。
      • 在调用 system() 期间 SIGCHLD 信号会被暂时搁置,SIGINT 和 SIGQUIT 信号则会被忽略。
      • 等同于 /bin/bash -c "cmd" 或者 exec("bash", "-c", "cmd")
    • 返回值
      • 如果 system()在调用 /bin/sh 时失败则返回 127,其他失败原因返回-1。
      • 若参数 string 为空指针(NULL),则返回非零值。
      • 如果system()调用成功则最后会返回执行 shell 命令后的返回值,但是此返回值也有可能为 system()调用 /bin/sh 失败所返回的 127,因此最好能再检查 errno 来确认执行成功。
    • 附加说明
      • 在编写具有SUID/SGID权限的程序时请勿使用 system(),system() 会继承环境变量,通过环境变量可能会造成系统安全的问题。

    26.1.2 system 应用

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <unistd.h>
     4 
     5 char *cmd = "date";
     6 
     7 int main(void)
     8 {
     9     system("clear");
    10     system(cmd);
    11 
    12     return 0;
    13 }

      编译执行

      

    26.1.3 构建 mysystem 命令

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <unistd.h>
     4 #include <sys/types.h>
     5 #include <sys/wait.h>
     6 
     7 char *cmd1 = "date > s1.txt";
     8 char *cmd2 = "date > s2.txt";
     9 
    10 void mysystem(char *cmd)
    11 {
    12     pid_t pid;
    13     if((pid = fork()) < 0) {
    14         perror("fork error");
    15         exit(1);
    16     } else if(pid == 0) {
    17         if(execlp("/bin/bash", "/bin/bash", "-c", cmd ,NULL) < 0) {
    18             perror("execlp error");
    19             exit(1);
    20         }
    21     } 
    22 
    23     wait(0);
    24 }
    25 
    26 int main(void)
    27 {
    28     system("clear");
    29     system(cmd1);
    30 
    31     mysystem(cmd2);
    32 
    33     return 0;
    34 }

      编译调试

      

    26.6 进程状态切换

      

    • runnable:就绪状态
    • running:运行状态
    • block/suspend:阻塞或挂起状态
    • dead:终止状态。正在运行的状态调用 return/exit_exit 进入 dead 状态
    • os scheduler:系统调度
  • 相关阅读:
    查看python关键字
    命令终端执行python
    Codeforces-462C. A Twisty Movement
    Codeforces-462A. A Compatible Pair
    Codeforces-446C. Pride
    Codeforces-Hello 2018C. Party Lemonade(贪心)
    Codeforces-33C. Wonderful Randomized Sum
    Codeforces-118D. Caesar's Legions(lazy dynamics)
    codeforces-73C. LionAge II
    Gym 101510C-Computer Science
  • 原文地址:https://www.cnblogs.com/kele-dad/p/9157864.html
Copyright © 2020-2023  润新知