gpt4 book ai didi

c - Fork-server 和 exec 的孙子

转载 作者:行者123 更新时间:2023-11-30 15:51:22 26 4
gpt4 key购买 nike

我需要有关 fork-server 的帮助。我想要做的是接受一个客户端,然后 fork 以让其他客户端连接,同时将 stdout 和 err 重定向到客户端。然后,客户端应该能够发送应由位于孙子中的 execlp() 执行的字符串。

我无法找到我的逻辑错误..

在 main() 中:

    while (1) {

t = sizeof(remote);

printf("Waiting for connection.\n");

s2 = accept(s, (struct sockaddr*)&remote, &t);

if (s2 == -1) {
perror("accept");
exit(1);
} else {

printf("Client connected.\n");

if(!fork()) {

close(1);
dup(s2);
handle(s2);
exit(0);
}
close(s2);
}
}

在句柄()中:

    char str[100];
int n;

while(1) {

n = recv(client_socket, str, 100, 0);

if(n <= 0) {

perror("recv");
exit(1);
} else {

if(!fork()) {

execlp("/bin/sh", "sh","­-c", str, NULL);
exit(1);
}
wait(0);
}
}

execlp 的结果没有重定向到客户端,并给出错误“sh: Can't open c”。

最佳答案

您应该编写: execlp("/bin/sh", "sh","-c", str, NULL); 将选项“-c”传递给 shell。您传递的选项 "c" 被解释为:运行名为 c 的脚本,该脚本不存在。

参见:http://unixhelp.ed.ac.uk/CGI/man-cgi?sh

另一件事:在读取字符串后,您应该 NUL 终止它:

if(n > 0)
str[n] = '\0';

您还应该只读取 99 个字符,因为您将在字符串末尾写入 '\0' 字符。

关于c - Fork-server 和 exec 的孙子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15159468/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com