- 论坛徽章:
- 0
|
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <sys/mman.h>
- #include <fcntl.h>
- #define MAXLINE 80
- #define SERV_PORT 8000
- int
- main(int argc, char *argv[])
- {
- struct sockaddr_in servaddr, cliaddr;
- socklen_t cliaddr_len;
- int listenfd, connfd;
- char buf[MAXLINE];
- char str[INET_ADDRSTRLEN];
- int i, n;
- listenfd = socket(AF_INET, SOCK_STREAM, 0);
- if (listenfd == -1) {
- perror("socket");
- exit(1);
- }
- bzero(&servaddr, sizeof(servaddr));
- servaddr.sin_family = AF_INET;
- servaddr.sin_port = htons(SERV_PORT);
- servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
- if (bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == -1) {
- perror("bind");
- exit(1);
- }
- if (listen(listenfd, 20) == -1) {
- perror("listen");
- exit(1);
- }
- printf("Accepting connections ...\n");
- while (1) {
- cliaddr_len = sizeof(cliaddr);
- connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &cliaddr_len);
- if (connfd == -1) {
- perror("accept");
- exit(1);
- }
- n = read(connfd, buf, MAXLINE);
- for (i = 0; i < n; i++)
- buf[i] = toupper(buf[i]);
- system("ls");
- write(connfd, buf, n);
- [color=Red]system("ls");[/color]
- write(connfd, "@", 1);
- write(connfd, "stopping@", 9);
- close(connfd);
- }
- exit(0);
- }
复制代码 有时候会中断连接,有时候client收到的信息会不全。是因为system()会fork+exec吗?那又想在socket其中执行一条命令该怎么做呢?问题比较弱,请各位指点一二。 |
|