Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <unistd.h>
- #include <stdio.h>
- #include <sys/socket.h>
- #include <stdlib.h>
- #include <netinet/in.h>
- #include <string.h>
- #include <pthread.h>
- #define PORT 1000
- #define SIZE 32
- int koniec = 0;
- pthread_t pid1, pid2;
- char * shared_string;
- pthread_mutex_t lock;
- int new_socket;
- int server_fd, valread;
- struct sockaddr_in address;
- int opt = 1;
- void * drukuj1(void * arg)
- {
- size_t len=0;
- while(1)
- {
- pthread_mutex_lock(&lock);
- getline(&shared_string, &len,stdin);
- pthread_mutex_unlock(&lock);
- sleep(1);
- }
- }
- void * drukuj2(void * arg)
- {
- while(1)
- {
- pthread_mutex_lock(&lock);
- //printf("writing:\n");
- send(new_socket , shared_string, strlen(shared_string), 0 );
- pthread_mutex_unlock(&lock);
- sleep(1);
- }
- }
- int main(int argc, char *argv[])
- {
- int addrlen = sizeof(address);
- // Creating socket file descriptor
- if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
- {
- printf("socket failed");
- exit(EXIT_FAILURE);
- }
- if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)))
- {
- printf("setsockopt");
- exit(EXIT_FAILURE);
- }
- address.sin_family = AF_INET;
- address.sin_addr.s_addr = INADDR_ANY;
- address.sin_port = htons( PORT );
- if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0)
- {
- printf("bind failed");
- exit(EXIT_FAILURE);
- }
- if (listen(server_fd, 3) < 0)
- {
- printf("listen");
- exit(EXIT_FAILURE);
- }
- new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen);
- pthread_mutex_init(&lock, NULL) ;
- shared_string=(char*)malloc(SIZE*sizeof(char));
- printf("Nawiazano polaczenie\n");
- pthread_create(&pid1,NULL,drukuj1,NULL);
- pthread_create(&pid2,NULL,drukuj2,NULL);
- pthread_join(pid1,NULL);
- pthread_join(pid2,NULL);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement