[英]File operations. A c program that will take a single command line argument using fork() execvp() , wait/waitpid()
[英]Using execvp,fork and wait to execute codes in file
我一直在使用 execvp 来执行写在文本文件中的 unix 命令。 下面是我写的代码,但它似乎不起作用。
我正在从文件中读取行,每行都包含一个 unix 命令(mv、cp 等)。
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include <unistd.h>
int main ( int argc, char *argv[] )
{ pid_t pid;
pid_t child_pid;
int child_status;
char *token;
FILE *fp;
fp = fopen(argv[1],"r");
int i,j,ctr,rc_wait;
if( fp == NULL){
perror("An error has occurred\n");
exit(1);
}
char buff[100];
while(fgets(buff, sizeof(buff), fp)){
child_pid=fork();
if(child_pid<0){
printf("\nfork failed, error");
exit(0);
}
else if(child_pid==0){
//printf("\nString value = %s", buff);
token = strtok(buff, " \t");
execvp(token,buff);
}
else{
rc_wait = wait(NULL);
continue;
}
}
}
return 0;
}
输入文件已作为参数提供给程序,输入包含以下示例:
cp temp1/f1.txt temp2/
mv temp1/f2.c temp2/
cp temp1/f3.txt temp2/
cp temp1/f4.txt temp2/
cp temp1/f5.txt temp2/
cp temp1/f6.txt temp2/
mv temp1/f7.c temp1/f8.c
mv temp1/f9.c temp2/
cp temp1/f1.txt temp1/f1a.txt
你在滥用strtok
和execvp
。 前者在您调用它时会改变输入字符串,因此在它运行一次之后,它会被一个NUL
拆分buff
( token
和buff
在第一次调用后实际上指的是同一个地址,尽管token
会在额外的标记化后发生变化)。 如果您在生成每个结果时复制每个结果(例如,如果您可以依赖现代 POSIX 标准,则通过strdup
),您只能使用strtok
来完全解析输入,因为只有最近返回的指针才是有效的。
你的execvp
用法也是错误的; execvp
的第二个参数是 C 样式字符串数组char*
s(数组本身以NULL
指针终止)。 您向它传递了一个普通的char
数组(一个字符串,而不是它们的数组)。
请阅读这两个 API 的man
页; 你离目标太远了,很明显你只是在猜测它们是如何工作的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.