fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <assert.h>
  5. #include <unistd.h>
  6. #include <pthread.h>
  7. #include <sys/types.h>
  8. #include <sys/wait.h>
  9. #include <sys/socket.h>
  10.  
  11. int is_client;
  12. int sp[2];
  13. const char *hdr[] = { "S:", "C:" };
  14. const char *msg[] = { "Server says hello.", "Client says hello." };
  15.  
  16. void * reader (void *arg) {
  17. const char *err[] = { "S:reader", "C:reader" };
  18. char buf[1024];
  19. (void)arg;
  20. strcpy(buf, hdr[is_client]);
  21. for (;;) {
  22. ssize_t r = recv(sp[is_client], buf+2, sizeof(buf)-2, 0);
  23. if (r > 0) {
  24. buf[r+2] = '\0';
  25. puts(buf);
  26. continue;
  27. }
  28. if (r < 0) perror(err[is_client]);
  29. break;
  30. }
  31. shutdown(sp[is_client], SHUT_RD);
  32. return 0;
  33. }
  34.  
  35. void * writer (void *arg) {
  36. const char *err[] = { "S:writer", "C:writer" };
  37. ssize_t n = strlen(msg[is_client]);
  38. ssize_t x = 0;
  39. (void)arg;
  40. while (x < n) {
  41. ssize_t r = send(sp[is_client], msg[is_client] + x, n - x, 0);
  42. assert(r != 0);
  43. if (r > 0) {
  44. x += r;
  45. continue;
  46. }
  47. if (r < 0) perror(err[is_client]);
  48. break;
  49. }
  50. shutdown(sp[is_client], SHUT_WR);
  51. return 0;
  52. }
  53.  
  54. void read_and_write (int c) {
  55. close(sp[!c]);
  56. is_client = c;
  57. pthread_t t[2];
  58. pthread_create(t+0, 0, reader, 0);
  59. pthread_create(t+1, 0, writer, 0);
  60. pthread_join(t[0], 0);
  61. pthread_join(t[1], 0);
  62. close(sp[c]);
  63. }
  64.  
  65. int main () {
  66. socketpair(PF_UNIX, SOCK_STREAM, 0, sp);
  67. switch (fork()) {
  68. default: read_and_write(0);
  69. break;
  70. case 0: read_and_write(1);
  71. exit(0);
  72. case -1: perror("fork");
  73. exit(0);
  74. }
  75. wait(0);
  76. return 0;
  77. }
  78.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
/home/sosGhm/ccLcScVk.o: In function `read_and_write':
prog.c:(.text+0x1e4): undefined reference to `pthread_create'
prog.c:(.text+0x208): undefined reference to `pthread_create'
prog.c:(.text+0x21c): undefined reference to `pthread_join'
prog.c:(.text+0x230): undefined reference to `pthread_join'
collect2: error: ld returned 1 exit status
stdout
Standard output is empty