![](/img/trans.png)
[英]How can I execute cat command using execvp or other kinds of exec functions in programming C
[英]How can I use execl() function or other kinds of exec() functions to perform echo command?
我有一個問題,我使用以下程序(fork()函數)創建了一個子進程以使用execl()重載另一個程序。 如果我想在execl()函數或其他類型的exec()函數中使用echo命令,該怎么辦? 我使用以下程序,但失敗了! 終端向我發出警告:回聲:無法訪問世界!:沒有此類文件或目錄是父目錄!
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{ pid_t childpid;
childpid=fork();
if(childpid==-1){
perror("failed to fork");
return 1;
}
if(childpid==0)
{
execl("/bin/ls","echo","hello world!",NULL);
perror("child failed to exec");
return 1;
}
if(childpid!=wait(NULL)){
perror("parent failed to wait due to signal or error");
return 1;
}
sleep(5);
printf("this is parent!\n");
return 0;
}
您正在執行的命令是:
/bin/ls "echo" "hello world!"
您可能要執行的是(假設您正在使用bash
):
/bin/bash -c 'echo "hello world!"'
因此使用:
execl("/bin/bash","-c","echo \"hello world!\"",NULL);
您可能想要在使用perror
之前檢查錯誤。
編輯:
根據EOF的建議,您可能應該使用system
調用而不是exec
。 它為您創建子流程,並讓您專注於手頭的任務(即調用shell命令)。 可能的缺點是它等待子進程終止后再繼續,但這很可能不是問題(無論如何在這種情況下都不是)。 它還會忽略某些信號( SIGINT
和SIGQUIT
),這可能是不希望的,具體取決於您如何設計程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.