[英]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.