简体   繁体   English

Execlp无法正常工作

[英]Execlp is not working

The user must type the command and the program should execute it. 用户必须键入命令,程序应执行它。 I am using fork() and execlp() but is not working. 我正在使用fork()和execlp(),但无法正常工作。 I am printing comando and ruta to see if they are good. 我正在打印comando和ruta,看它们是否很好。 I dont know how to make it different in order to make it work. 我不知道如何使其与众不同才能使它起作用。

#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 is not executung command because of fgets() , in above fgets() copies new line at the end of comando . execlp不executung命令由于fgets()在上述fgets()new line在末端comando see the manual page of fgets() 参见fgets()的手册页

Remove the new line as 删除新行为

fgets(comando,sizeof(comando),stdin); 
comando[strlen(comando)-1] ='\0'; /* replacing '\n' with '\0' */

OR you can use strcspn() below as suggested by @Jonathan Leffler. 或者,您可以按照@Jonathan Leffler的建议使用以下strcspn()

comando[strcspn(comando, "\n"))] = '\0';

Complete working code 完整的工作代码

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;
}

Not all executables are in /bin . 并非所有可执行文件都在/bin The point of execlp and the other exec functions with p in the name is that they look for the requested program in $PATH for you. execlp其他名称p exec函数的要点是它们在$PATH为您寻找所需的程序。

To help debug this kind of thing in the future, or if this doesn't work, you should check errno after every system call (which is what perror does after you fork ). 为了将来帮助调试这种事情,或者如果它不起作用,则应该在每个系统调用之后检查errno (这是在fork之后perror所做的事情)。 When exec*() -family functions work, they don't return; exec*() family函数工作时,它们不返回; when they fail, they set errno appropriately before returning. 当它们失败时,他们会在返回之前适当地设置errno

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM