linux系统txt文本里有几行指令,我想把他们存到char指针数组然后fork用execvp去执行这些指令,想一次性把图片里的三个指令运行了,希望好心人帮忙解决问题。

C语言编程问题求帮助帮忙
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- bear_priestess 2017-10-14 12:54关注
/*-----------------------------------------------------------------*/
/* This file is modified based on /
/ http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/fork/shell.c /
/ Enjoy your learning. Good luck. /
/-----------------------------------------------------------------*/#include
#include
#includevoid parse(char line, char **argv)
{
while (*line != '\0') { / if not the end of line ....... /
while (*line == ' ' || *line == '\t' || *line == '\n')
*line++ = '\0'; / replace white spaces with 0 /
*argv++ = line; / save the argument position /
while (*line != '\0' && *line != ' ' &&
*line != '\t' && *line != '\n')
line++; / skip the argument until ... /
}
*argv = '\0'; / mark the end of argument list */
}void execute(char **argv)
{
pid_t pid;
int status;if ((pid = fork()) < 0) { /* fork a child process */ printf("*** ERROR: forking child process failed\n"); exit(1); } else if (pid == 0) { /* for the child process: */ if (execvp(*argv, argv) < 0) { /* execute the command */ printf("*** ERROR: exec failed\n"); exit(1); } } else { /* for the parent: */ while (wait(&status) != pid); /* wait for completion */
;
}
}void main(void)
{
char *argv[60];
FILE *fp;
fp = fopen("a.txt","r");
char * line = NULL;
size_t len = 0;
ssize_t read;
while ((read = getline(&line, &len, fp)) != -1)
{
printf("bash: %s", line);
line[read -1]='\0';
parse(line, argv);
execute(argv);
}
}写了指令的文件放在同一目录下
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报