sp; }
close( sockfd );
close( connfd );
exit ( 0 );
}
else
close( connfd );
}
3.3.3 执行命令函数
int command(int connfd,char*command)
{
/*
* 作用:通过popen调用shell执行command命令
* connfd: 客户端标识
* command: 命令字符串
*/
FILE *fstream = NULL;
char buff[1024];
memset(buff, 0, sizeof(buff));
if ( strcmp(exit_command, command) == 0 ) { //退出
if ( send(connfd, exit_command,strlen(exit_command), 0) < 0 )
printf( "send failed" );
printf("客户端已断开连接!\n");
return 0;
}
if(NULL == (fstream = popen(command,"r")))
{
fprintf(stderr,"execute command failed: %s",strerror(errno));
return -1;
}
while(NULL != fgets(buff, sizeof(buff), fstream))
{
//printf("%s",buff);
if ( send(connfd, buff,strlen(buff), 0) < 0 ) //将命令执行结果发送至客户端
printf( "send failed" );
}
pclose(fstream);
return 0;
}
3.3.4客户端发送与接受信息
int send_recv( int connfd,char flag )
{
/*
* 作用:客户端与服务器端信息的处理
* connfd: 服务器端标识
* flag: 输入类比标识
*/
char input_buf[ BUF_SIZE ]; //定义字符串存放输入信息
char recv_buf[ BUF_SIZE ]; //定义字符串存放服务器端返回信息
memset(input_buf, 0, sizeof(input_buf));
memset(recv_buf, 0, sizeof(recv_buf));
fgets( input_buf, BUF_SIZE, stdin ); //获取用户输入
input_buf[strlen(input_buf) - 1] = '\0'; //去除最后一个输入的确认
/* 向服务器发送消息 */
if ( send(connfd, input_buf, BUF_SIZE, 0) < 0 )
printf( "send failed" );
&