gpt4 book ai didi

c - 使用 fork() 和 execvp() 函数创建 C 程序时遇到问题

转载 作者:行者123 更新时间:2023-11-30 17:04:27 25 4
gpt4 key购买 nike

这是我目前遇到问题的以下代码:

#include <stdio.h>
#include <unistd.h>
#include<sys/types.h>
#include<sys/wait.h>

#define MAX_LINE 80

int main(void)
{
char *args[MAX_LINE/2+1];
int background= 0;//integer that acts a boolean for if & appears
int should_run = 1;
int status;

while(should_run)//Just to keep the interface going until the user chooses to stop
{
printf("osh>");//prompt
fflush(stdout);

int i = 0;
while(getchar() != '\n')//Use scanf until a new line is found
{
scanf("%s", &args[i]);

if(strcmp(&args[i], "exit") == 0)//temporary exit protocal
{
printf("Exiting now...");
return 0;
}


if(strcmp(&args[i], "&") == 0)//If we find a & in our input then we changed background to 1 or true
background = 1;
printf("Args[%i] = %s\n", i, &args[i]);//Tester
i++;
}


printf("Background = %i\n",background);//Test
pid_t pid= fork();// Create new child process
printf("process %i created\n", pid);//Test



if(pid < 0)//fork() failed
{
printf("Fork Failed.\n");
return 1;
}

else if(pid == 0)//Child process id
{
printf("Child process started %s command\n", &args[0]);
if(execvp(args[0], args) < 0)//change the current child process to execute the input given by the user
//with args[0] being the command and args being the parameters(ls -l is an example).
{
printf("Command failed\n");
}
return 0;
}

else//Parent Process
{
if(background == 1)//If the user typed in a & then the parent will wait for a change in state from the child, if there is no &
//then we will just finish the parent process
{
printf("Parent process waiting on child\n");
wait(NULL);
}
}

}

return 0;

我现在有一个主要问题和一个小问题。主要问题是我在 execvp 启动之前有一个 printf 方法,上面写着“子进程已启动”,并且我打印了这一行,但之后什么也没有发生。没有引发中断,程序似乎被我的 execvp 命令卡住了。

我的小问题是,当我的程序在要求输入之前启动提示符“osh>”时。现在,例如,如果我输入“osh>ls -l”,那么我会得到 args[0] = s, args 1 =-l。现在,如果我以确切的格式输入“osh> ls -l”,我会得到 args[0] = ls, args 1 =-l。这是我在这里没有正确使用的 scanf() 的一部分,以确保我在“osh>”之后以及空格之间获得字符作为字符串吗?

编辑:这是我的用户输入“ls -l”的输出 Output for prog.c

最佳答案

您遇到的缺少字符的问题是因为 getchar()scanf 尝试之前消耗了输入的第一个字符。您可能想做类似的事情:

while (scanf("%s", &buffer) > 0)
{
strcpy(args[i], buffer);
/* then do stuff with args[i] */
}

关于c - 使用 fork() 和 execvp() 函数创建 C 程序时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35782677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com