- 论坛徽章:
- 0
|
能不能exec一个干净的环境,不复制父进程的资源呀,以下是我的测试部分代码,如果我想把程序执行的输出到客户端(重定向,可是socket要关闭才没有问题),该怎么办呀,请各位大侠能否帮帮我,我才学unix下的c编程:
static void sigchild_handler(int signo)
{
pid_t pid;
int status;
while(pid = waitpid(-1, &status, WNOHANG|WUNTRACED) > 0) {;};
}
void child(int listen_sock, int sock)
{
int read_fd;
int write_fd;
FILE * in;
FILE * out;
char * s;
int cfd;
char * buf;
struct stat conf_stat;
read_fd = dup(sock);
write_fd = dup(sock);
in = fdopen(read_fd,"r");
out = fdopen(write_fd,"w");
fprintf(out,"220 localhost ServerAdmin\r\n");
fflush(out);
sleep(1);
cfd = open(config_file, O_RDONLY);
if(cfd == -1)
haserror(config_file);
fstat(cfd, &conf_stat);
buf = malloc(conf_stat.st_size * sizeof(char));
read(cfd, buf, conf_stat.st_size);
fprintf(out,"%s", buf);
free(buf);
int pid=fork();
fclose(in);
fclose(out);
if (pid==0) {
close(sock); /*不关闭这两行的话,socket的资源就不释放,要等daemon退出才可以*/
close(listen_sock);
signal(SIGCHLD, SIG_DFL);
system("/etc/init.d/apache2 stop");
system("/etc/init.d/apache2 start");
exit(0);
}
printf("pid is %d\n", pid);
}
int server_process()
{
pid_t pid;
int rc;
int fd;
int listen_sock;
struct timeval tv;
int port = server_port;
struct sockaddr_in tcp_addr;
struct sockaddr_in remote_addr;
int addr_size = sizeof(remote_addr);
int sock;
tcp_addr.sin_family = AF_INET;
tcp_addr.sin_addr.s_addr = INADDR_ANY;
printf("%s", INADDR_ANY);
tcp_addr.sin_port = htons(port);
listen_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
if (listen_sock == -1)
haserror("Socket create error");
rc = bind(listen_sock, (struct sockaddr *) &tcp_addr, sizeof(tcp_addr));
if (rc == -1)
haserror("Bind false");
rc = listen(listen_sock, 128);
if (rc == -1)
haserror("Listen false");
rc = fork();
if (rc == -1)
{
haserror("Fork false");
} else if (rc > 0) {
printf("Daemon start success\n");
exit(0);
} else {
signal(SIGCHLD, sigchild_handler);
for (;;) {
sock = accept(listen_sock, (struct sockaddr *) &remote_addr, &addr_size);
if (sock == -1 && errno == EINTR)
continue;
rc = fork();
if (rc == -1)
haserror("Fork false");
else if (rc > 0) {
close(sock);
continue;
}
child(listen_sock, sock);
close(sock);
break;
}
}
close(listen_sock);
}
[ 本帖最后由 guxing1841 于 2006-6-21 11:56 编辑 ] |
|