【发布时间】:2019-06-03 12:34:34
【问题描述】:
我已经创建了一个类似 bash 的程序,但是当我尝试执行它时,它在第一次运行良好,但在它没有按预期运行之后
最后执行的输出重复显示而不是询问新的输入
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/wait.h>
char full_cmd[20];
void command_source(char *cmd)
{
FILE *fp;
char output[20];
char *token;
token = strtok(cmd," ");
strcpy(full_cmd,"which ");
strcat(full_cmd,token);
fp = popen(full_cmd,"r");
while (fgets(output, 20, fp) != NULL) {
strcpy(full_cmd,output);
}
full_cmd[strlen(full_cmd)-1] = '\0';
token = strtok(NULL," ");
while (token != NULL)
{
strcat(full_cmd,token);
token = strtok(NULL," ");
}
}
void get_input(char input[10])
{
printf("Enter the command:");
scanf("%[^\n]s",input);
}
int launch_shell(char *buff[50],int status)
{
pid_t pid = fork();
if( pid == 0 )
{
execv(buff[0],buff);
}
else if (pid > 0)
{
pid_t wpid = waitpid(pid, &status, 0);
}
else
return 0;
return 1;
}
int main()
{
char *buff[50];
int status;
char input[10];
int count=0,ret=1;
while(ret == 1)
{
get_input(input);
command_source(input);
strcpy(buff[0],full_cmd);
buff[1] = NULL;
int ret = launch_shell(buff,status);
}
}
预期:
Enter the command:ls
server.c server
Enter the command:ls -l
server.c
server
实际结果:
Enter the command:ls
server server.c
server server.c
server server.c
server server.c
server server.c
server server.c
server server.c
server server.c
server server.c
server server.c
server server.c
server server.c
server server.c
server server.c
...
请帮助我找出问题所在。我花了一整天来解决这个问题。但我做不到。
【问题讨论】:
-
您忽略了 scanf() 的返回值,风险自负。考虑不要。
标签: c multiprocessing fork