fork download
  1. #include <sys/wait.h>
  2. #include <unistd.h>
  3. #include <sys/shm.h>
  4. #include <sys/ipc.h>
  5. #include <sys/stat.h>
  6. #include <sys/types.h>
  7. #include <iostream>
  8. #include <string>
  9. using namespace std;
  10.  
  11.  
  12. int main(){
  13. string s="Hello, World!";
  14.  
  15. pid_t pid;
  16. int shm_id;
  17. if((shm_id=shmget(IPC_PRIVATE,sizeof(int),IPC_CREAT|0666))<0){
  18. perror("shmget");
  19. return 0;
  20. }
  21. int *shm_addr;
  22. if((shm_addr=(int *)shmat(shm_id,NULL,0))==(int*)-1){
  23. perror("shmat");
  24. return 1;
  25. }
  26.  
  27. for(int i=0;i<s.size();i++){
  28. pid=fork();
  29. if(pid==-1)
  30. cout<<"fork error"<<endl;
  31. else if(pid==0)
  32. break;
  33. else
  34. continue;
  35. }
  36.  
  37. if(pid>0){
  38. for(int i=0;i<s.size();++i)
  39. wait(NULL);
  40. sleep(1);
  41. if((shmctl(shm_id,IPC_RMID,0))==-1){
  42. perror("shmctl");
  43. exit(-1);
  44. }
  45. cout<<endl;
  46.  
  47. }else{
  48.  
  49. int *sp=(int*)shmat(shm_id,NULL,0);
  50. sleep(2);
  51. cout<<s[*sp];
  52. (*sp)++;
  53. exit(0);
  54. }
  55. return 0;
  56. }
Success #stdin #stdout 0s 15248KB
stdin
Standard input is empty
stdout
Hello, World!