|
楼主 |
发表于 2005-3-17 14:45:44
|
显示全部楼层
我得最终程序是这样的:
[code:1]#define MYPORT 5002
#define MAX 100
#define FIFO "fifo"
#define BACKLOG 1
static int stop = 0;
static int shall_pid=0;
static char *pbuf;
void convert(int n,char * buf)
{
int i;
pbuf=buf;
if((i=n/10)!=0)
convert(i,pbuf);
*pbuf=n%10+48;
pbuf+=1;
*pbuf='\n';
}
int main(){
char buf[100]={'\0'};
char kbuf[100]={'\0'};
char outbuf[100]={'\0'};
char pkill;
static int pid,pid2,ppid;
static int stop=0;
int pipes[2];
int rc,i,j,x;
int sockfd, new_fd;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
int sin_size;
int state;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket");
exit(1);
}
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(MYPORT);
my_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(my_addr.sin_zero), 8);
if (bind(sockfd, (struct sockaddr *)&my_addr,
sizeof(struct sockaddr)) == -1)
{
perror("bind");
exit(1);
}
if (listen(sockfd, BACKLOG) == -1)
{
perror("listen");
exit(1);
}
sin_size = sizeof(struct sockaddr_in);
if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) {
perror("accept");
}
printf("server: got connection from %s\n", inet_ntoa(their_addr.sin_addr));
rc=pipe(pipes);
if (rc == -1) {
perror("pipe error");
exit(0);
}
switch( pid2=fork() ) {
case -1:
exit(0);
case 0: {
dup2(pipes[1],1);
dup2(pipes[1],2);
for ( ; ; ) {
memset(buf,'\0',MAX);
if ((recv(new_fd, buf, 100, 0)) == -1) {
continue;
}
printf("\nyou input: %s\n",buf);
//中止shall命令的执行
if ( strcmp(buf,"-quit\n")==0 ) {
printf("shall pid is %d\n",shall_pid);
memset(kbuf,'\0',MAX);
strcpy(kbuf,"kill ");
convert(shall_pid,&kbuf[5]);
system(kbuf);
printf("to kill %s\n",kbuf);
printf("%s...get the quit message.\n",kbuf);
memset(buf,'\0',MAX);
continue;
}
if (strcmp(buf,"quit\n")==0) {
stop=1;
printf("quit\\0");
memset(kbuf,'\0',MAX);
strcpy(kbuf,"kill ");
convert(shall_pid,&kbuf[5]);
system(kbuf);
convert(pid,&kbuf[5]);
system(kbuf);
exit(0);
}
switch( ppid=fork() ) {
case -1:
_exit(0);
case 0: {
switch( shall_pid=fork() ) {
case -1:
_exit(0);
case 0: {
printf("shall pid is %d at child \n",(shall_pid=getpid()));
execl("/bin/sh","sh","-c",buf,(char *) 0);
_exit(0);
}
default: {
printf("exit %d..",shall_pid);
sleep(1);
_exit(0);
}
}
}
default: {
wait(&ppid);
}
}
}
_exit(0);
}
default:
break;
}
pid = fork();
switch ( pid ) {
case -1:
exit(0);
case 0: {
for ( ; ; ) {
if (stop==1) {
break;
}
if ((i=read(pipes[0],outbuf,MAX-1))>0) {
outbuf[MAX-1]='\0';
if (strcmp(outbuf,"quit\\0")==0) {
break;
}
if ( send(new_fd,outbuf, MAX, 0)==-1)
printf("send error\n");
memset(outbuf,'\0',MAX);
} else break;
}
_exit(0);
}
default:
break;
}
printf("send pid:%d recv pid:%d\n",pid,pid2);
wait(&pid2);
wait(&pid);
close(new_fd);
close(sockfd);
close( pipes[0] );
close( pipes[1] );
return 0;
}[/code:1]
程序产生两个进程,一个接受客户端发来的shall命令并将输出定向到管道,一个从管道中读取后发给客户端。现在的问题是如果客户端发出ping 192。168。0。1而后输入-quit时,程序不安正常的代码执行,甚至连 //中止shell命令的执行
的部分代码也没有执行。 |
|