【问题标题】:C: Multi process CMD does nothing after running all commandsC: 多进程 CMD 运行完所有命令后什么都不做
【发布时间】:2019-12-07 05:45:49
【问题描述】:

我是用 C 语言做的,它确实同时运行所有命令。但最后,它将最后一个命令放在 CMD 的用户输入部分,然后什么也不做。 这是命令的输出:

hen03:~/Lab_08> ./assign8 whoami , ls -a , pwd
Child Process: PID=11895, PPID=11894, Command=whoami
Child Process: PID=11897, PPID=11894, Command=pwd
Child Process: PID=11896, PPID=11894, Command=ls
/home/uid454/Lab_08
hen03:~/Lab_08> .  ..  assign8  assign8.c  makefile  uid454.zip
uid454

hen03:~/Lab_08>  

这是我写的代码

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

void startProcesses(int commands, char *commandList[6][100]){
    static pid_t forks[6];
    int status[6];
    int i;

    for(i = 0; i < commands; i++){
      switch(forks[i] = fork()){
            case -1: //failed
            perror("fork failed");
                break;
            case 0: //child does things 
                printf("Child Process: PID=%ld, PPID=%ld, Command=%s\n", (long) getpid(), (long) getppid(), commandList[i][0]);
                if(execvp(commandList[i][0], commandList[i]) < 0){
                    printf("something failed\n");
                }
                break;
            default:
                if(i == commands-1){
                    waitpid(forks[i], &status[i], 0);
                }
        }
    }
}

int main(int argc, char *argv[])
{
    int commandNum = 0, index, numOfCommands = 1, j =0;
    static char *commandList[6][100];

    //start of separate algo
    for (index = 1; index < argc; index++){
        if(strcmp(strtok(argv[index], " "), ",") == 0){
            commandNum++;
            numOfCommands++; 
            commandList[commandNum-1][j] = NULL;
            j = 0;
            continue;
        }
        else{
            commandList[commandNum][j] = argv[index];
            j++;
        }

    }
    //end of separation algo

    startProcesses(numOfCommands, commandList);
    return 0;
}

老实说,我不知道问题出在哪里,也不知道如何在谷歌上搜索它。有人可以解释为什么这样做吗?

编辑:取出行号

【问题讨论】:

  • 请不要在您的示例中包含行号,这会使我们自己尝试它变得更加困难。如果您想引起我们注意的特定行,请对其添加评论并在问题正文中提及。
  • 如果你把ls -a 作为第一个命令会发生什么?我怀疑你的解析有问题
  • 它运行得很完美......但仍然不知道为什么
  • 好吧,我的预期正好相反 :) 然后就是别的了。

标签: c cmd concurrency


【解决方案1】:

某些子进程的输出是否显示在 shell 提示符上?

那是因为您不等待所有子进程,只等待最后一个。并且无法保证子进程将以任何特定顺序执行。

这意味着您的父进程可以在所有子进程完成之前退出,这意味着 shell 重新控制并显示提示。

你真的应该等待所有子进程。如果您希望子进程并行运行,最好在第二个循环中。

【讨论】:

  • 如果我都等着他们,难道不是等到那个孩子做完然后再去下一个吗?这看起来就像一个正常的循环,而不是并行运行它们。
  • @MarchingDelta 这就是为什么我建议您在分叉所有子进程之后在单独的循环中进行等待。
  • 那行得通。但是如果父进程在子进程完成之前退出,他们不会成为孤儿并且 ppid 为 1 吗?
  • @MarchingDelta 是的,但这是不好的行为。此外,正如您在程序中看到的那样,可能会在您的程序之外产生其他后果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-01
  • 2016-02-28
  • 2017-03-22
  • 1970-01-01
  • 2021-09-16
相关资源
最近更新 更多