【发布时间】: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