C - 分叉执行等待退出并显示错误代码



我正在编写自己的类似shell的程序,exec*函数调用时不断出现错误。

以下是核心processes.c的源代码:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/uio.h>
#define BUFSIZE 128
#define EXIT_STR "exit"
int main(int argc, char ** argv) {
    const char *prompt = "> ";
    char buffer[BUFSIZE];
    int bytes_read;
    int status;
    pid_t child_p;
    while(1) {
        printf("%s", prompt);
        fflush(stdout);
        bytes_read = read(0, buffer, BUFSIZE);
        buffer[bytes_read-1] = '';
        if(strncmp(EXIT_STR, buffer, bytes_read) == 0)
            exit(0);
        if((child_p = fork()) == 0) {
            printf("[*] %d executing: %sn", getpid(), buffer);
            execlp(buffer, buffer);
            printf("[*] %d got error on execlpn", getpid());
            exit(1);
        } else {
            waitpid(child_p, &status, 0);
            printf("[*] child returned: %dn", status);
        }
    }
}

我也有简单的other.c测试程序:

#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv){
    printf("Hello. I am %s with pid: %dn", argv[0], getpid());
    exit(0);
}

我在MacOS High Sierra上使用llvm进行编译:

 $  llvm-gcc processes.c -o processes -Wall
 $  ./processes
> other
[*] 6040 executing: other
[*] 6040 got error on execl
[*] child returned: 256
> ls
[*] 6041 executing: ls
[*] 6041 got error on execl
[*] child returned: 256
> exit

我错过了什么?

一起

,要execlp()的第二个参数参数和任何后续参数对应于在其参数向量中提供给新程序main()函数的字符串。 它们都必须都是指向以 null 结尾的 C 字符串的指针,但列表的末尾必须char * 类型的 null 指针标记。 例如:

execlp(buffer, buffer, (char *) NULL);

这是此函数参数的记录要求,如果不满足它,程序邮件将失败。 如果您愿意,您可以将其合理化为为系统提供一种计算参数向量元素的方法,以便将该数字传递给新的main()。 您还可以认为参数向量本身被记录为由空指针终止。

相关内容

最新更新