[英]Execlp is not working
用戶必須鍵入命令,程序應執行它。 我正在使用fork()和execlp(),但無法正常工作。 我正在打印comando和ruta,看它們是否很好。 我不知道如何使其與眾不同才能使它起作用。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include<string.h>
int main(){
char comando[10];
char ruta[40];
printf("Type a command: ");
fgets(comando,10,stdin);
pid_t pid;
pid = fork();
if (pid < 0){
perror("Error");
return -1;
}
else if (pid == 0){
strcpy (ruta,"/bin/");
strcat (ruta,comando);
printf("%s",ruta);
printf("%s",comando);
execlp(ruta, comando,NULL);
}
else{
wait(NULL); }
return 0;
}
execlp
不executung命令由於fgets()
在上述fgets()
份new line
在末端comando
。 參見fgets()
的手冊頁
刪除新行為
fgets(comando,sizeof(comando),stdin);
comando[strlen(comando)-1] ='\0'; /* replacing '\n' with '\0' */
或者,您可以按照@Jonathan Leffler的建議使用以下strcspn()
。
comando[strcspn(comando, "\n"))] = '\0';
完整的工作代碼
int main(){
char comando[10];
char ruta[40];
printf("Type a command: ");
fgets(comando,sizeof(comando),stdin);
comando[strlen(comando)-1] ='\0';
pid_t pid;
pid = fork();
if (pid < 0){
perror("Error");
return -1;
}
else if (pid == 0){
strcpy (ruta,"/bin/");
strcat (ruta,comando);
execlp(ruta, comando,NULL);
}
else{
wait(NULL);
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.