c语言uf有循环的意思吗,c - 在while循环中使用execvp和fork时的无限循环 - SO中文参考 - www.soinside.com...

我正在尝试编写一个小shell程序,我希望它在调用另一个程序后通过execvp()保持活动状态。我希望fork系统调用“复制”该过程,创建一个几乎相同的发布(父)进程的副本(子)。因此,当父母因为excevp()呼叫而终止时,孩子们将仍然活着。

在下面附带的代码中,我读了一个用户输入(程序和要执行的参数),然后我希望父fork将执行程序,子fork将等待用户的下一个输入,但是在第一次之后我插入输入(要执行的程序及其参数),程序陷入无限循环。当子fork获得控制权时,它执行前一个程序并且不等待新的输入(似乎在第一个fgets()之后它不再等待用户输入)。

这是代码中有问题的部分:

#include

#include

#include

#include "LineParser.h"

#include

#include

char buf[PATH_MAX];

char buf_user[2048];

int pid;

void execute(cmdLine* pCmdLine) {

int pid = fork();

if(pid != 0) {

printf("I'm the parent.\n");

if(execvp(pCmdLine->arguments[0], pCmdLine->arguments) == -1) {

perror("execute failed");

_exit(1);

}

} else {

freeCmdLines(pCmdLine);

}

}

int main(int argc, char *argv[])

{

while(1) {

getcwd(buf, PATH_MAX);

printf("%s> ", buf);

fgets(buf_user, 2048, stdin);

fflush(stdin);

if(strcmp(buf_user, "quit\n") == 0) {

exit(0);

}

cmdLine* parsedCmd = parseCmdLines(buf_user);

execute(parsedCmd);

}

return 0;

}

cmdLine结构:

#define MAX_ARGUMENTS 256

typedef struct cmdLine

{

char *const arguments[MAX_ARGUMENTS]; /* command line arguments (arg 0 is the command) */

int argCount; /* number of arguments */

char const *inputRedirect; /* input redirection path. NULL if no input redirection */

char const *outputRedirect; /* output redirection path. NULL if no output redirection */

char blocking; /* boolean indicating blocking/non-blocking */

int idx; /* index of current command in the chain of cmdLines (0 for the first) */

struct cmdLine *next; /* next cmdLine in chain */

} cmdLine;

/* Parses a given string to arguments and other indicators */

/* Returns NULL when there's nothing to parse */

/* When successful, returns a pointer to cmdLine (in case of a pipe, this will be the head of a linked list) */

cmdLine *parseCmdLines(const char *strLine); /* Parse string line */

/* Releases all allocated memory for the chain (linked list) */

void freeCmdLines(cmdLine *pCmdLine); /* Free parsed line */

/* Replaces arguments[num] with newString */

/* Returns 0 if num is out-of-range, otherwise - returns 1 */

int replaceCmdArg(cmdLine *pCmdLine, int num, const char *newString);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值