C
You'd have written what you'd like to do.Now you facing challenges. socket♪ bind and listen in one process, a accept In another one. Single variables are different, but connectnecessary to establish communication SOCK_STREAM No, no, no, no.The network is full of examples of client-server code. See how he's written, and you'd better start reading something about multiprocess sockets.UpdatingThere was a free time, and I also wrote an example. Unix Domain STREAM socket client and server in one flaccoon (in the sense of one file). Server takes the lines from the client(s) and takes them out in a new xterm window.You might find something useful in synchronizing processes, launching servers in the background, completing, etc.Ended source file: https://drive.google.com/file/d/0BzY1LBmZNGbwamZfVTc0YXhVb2M/view?usp=sharing If the reference is not read, please inform the commentary here and I will rewrite the code to pastebin.If you don't understand anything, ask, try to explain.UpdateDecided to put the code in here./*
Совсем простой клиент-сервер.
Сервер всегда запускается в дочернем процессе и обслуживает 1-го клиента.
Клиент соединяется с этим сервером, шлет ему строки с клавиатуры
и читает ответ.
При завершении (Ctrl-D) клиента сервер тоже завершается.
Все сообщения клиента и сервера выводятся в окно, в котором запущена программа
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <signal.h>
#define ADDR "/tmp/usock_test1"
// макросы конкретно для этой программы
#define fatal(t) (kill(server, SIGTERM), perror(t), exit(-1))
#define sfatal(t) (kill(getppid(), SIGTERM), perror(t), exit(-1))
int
main (int ac, char *av[])
{
int sock, addrlen, l,
synch[2];
struct sockaddr_un saddr;
char buf[LINE_MAX];
pid_t server = 0;
// результат этих 4 строк унаследуется в обеих процессах
// он нужен для bind в сервере и connect в клиенте
// клиент должен дождаться, пока сервер стартует.
// синхронизируем их через pipe.
saddr.sun_family = AF_UNIX;
strcpy(saddr.sun_path, ADDR);
addrlen = sizeof(saddr.sun_family) + strlen(ADDR);
pipe(synch);
if ((server = fork())) { // client
puts("Client");
// ждем старта сервера, если что-то пойдет не так, он убъет клиента
read(synch[0], buf, 1);
// сделаем сокет, уже отделившись от сервера
sock = socket(AF_UNIX, SOCK_STREAM, 0);
if (connect(sock, (struct sockaddr *)&saddr, addrlen))
fatal("connect");
// цикл чтения клавиатуры, отсылки серверу и чтения эха
while (printf("Enter: "), fflush(stdout), fgets(buf, sizeof(buf), stdin)) {
buf[l = strlen(buf) - 1] = 0; // удалим \n в конце строки
if (write(sock, buf, l) != l)
fatal("client write");
if ((l = read(sock, buf, sizeof(buf) - 1)) < 1)
fatal("client echo read");
puts(buf);
}
} else { // server
// у сервера и клиента сокеты должны быть разными (у каждого свой)
sock = socket(AF_UNIX, SOCK_STREAM, 0);
unlink(ADDR); // if other server die ...
if (bind(sock, (struct sockaddr *)&saddr, addrlen) ||
listen(sock, 5)) // что-то не так, убъем клиентский процесс
sfatal("server");
printf ("Server %d\n", (int)getpid());
write(synch[1], "", 1); // все равно какой байт послать
if (close(synch[1]) == -1)
sfatal("server pipe");
// инициализация сервера завершена
int sfd = accept(sock, 0, 0);
if (sfd == -1)
sfatal("accept");
// echo цикл обслуживания одного клиента
while ((l = read(sfd, buf, sizeof(buf) - 1)) > 0) {
char buf2[LINE_MAX];
buf[l] = 0;
l = snprintf(buf2, LINE_MAX, "Echo: %s", buf);
if (write(sfd, buf2, l) == -1)
sfatal("server write");
}
perror("server exit");
// с клиентом больше нет связи
exit(0); // для простоты ничего не поверяем и не чистим
}
return puts("\nBye") == EOF; // клиентская часть
}
I hope it's really simple (although m.b. and not always good), there's a lot of comments in the code.Translating and launching without any keys.