Advertisement
Guest User

Untitled

a guest
Jan 26th, 2020
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 24.90 KB | None | 0 0
  1. #include <iostream>
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4. #include <sys/wait.h>
  5. #include <vector>
  6. #include <fstream>
  7. #include <fcntl.h>
  8. #include <sys/types.h>
  9. #include <sys/ipc.h>
  10. #include <sys/shm.h>
  11. #include <sys/types.h>
  12. #include <sys/ipc.h>
  13. #include <sys/sem.h>
  14.  
  15. #define MAX_BUFFER 100
  16.  
  17. ///EJERCICIO 1
  18. //Crea un proceso que cree tres procesos hijos de forma secuencial. Los hijos no deben existir a la vez.
  19. //El hijo 2 se generará cuando muera el 1 y el 3 cuando muera el 2
  20. //Evita los procesos zombie
  21.  
  22. int main(){
  23. for(int i = 0; i < 3; ++i){
  24. pid_t pid = fork();
  25. if(pid != 0){
  26. int test;
  27. wait(&test);
  28. }
  29. else{
  30. std::cout << "Soy el hijo" << getpid();
  31. return 0;
  32. }
  33. }
  34. return 0;
  35. }
  36.  
  37. ///EJERCICIO 3
  38. //Crea un proceso que cree un hijo que a su vez abra un firefox.
  39. //Evita que el hijo quede zombie antes de cerrar el padre.
  40.  
  41. int main(){
  42. pid_t pid = fork();
  43. if(pid == 0){
  44. execl("usr/bin/chrome", (char*)0);
  45. std::cout << "Esto no debería salir" << std::endl;
  46. }
  47. else{
  48. int status;
  49. wait(&status);
  50. std::cout << "Se cerró el Firefox." << std::endl;
  51. }
  52. }
  53.  
  54. ///EJERICIO 4
  55. //Crea un proceso que cree dos procesos hijo que abran Firefox y LibreOffice respectivamente.
  56. //Evita que queden zombies antes de acabar el padre.
  57.  
  58. int main(){
  59. pid_t pid1, pid2;
  60. int status1, status2;
  61.  
  62. if(pid1 = fork() == 0){
  63. execl("/usr/bin/firefox", (char*)0);
  64. std::cout << "Error al ejecutar el hijo 1." << std::endl;
  65. }
  66. else{
  67. if(pid2 = fork() == 0){
  68. execl("/usr/bin/google-chrome", (char*)0);
  69. std::cout << "Error en la creación del hijo 2" << std::endl;
  70. }
  71. else{
  72. //Esperamos a que finalice el hijo 2.
  73. waitpid(pid2, &status2, 0);
  74. }
  75. //Esperamos a que finalice el hijo 1.
  76. waitpid(pid1, &status1, 0);
  77. }
  78. //Padre acaba de ejecutarse cuando ambos hijos han finalizado.
  79. std::cout << "Los hijos han finalizado con exito, soy el padre" << std::endl;
  80. return 0;
  81. }
  82.  
  83. ///EJERCICIO 5
  84. //Crea un programa en c++ desed Code::BLocks que printe del 1 al 1000
  85. //Crea otro programa que contenga un proceso que cree dos procesos hijos. Desde cada uno de los hijos debe llamarse al programa anterior.
  86. //Comprueba como el dispatcher hace su trabajo.
  87. //Evita que los procesos queden zombies antes de acabar el padre.
  88.  
  89. void counter(){
  90. for(int i = 0; i < 1000; ++i){
  91. std::cout << i << " ";
  92. }
  93. std::cout << std::endl;
  94. }
  95.  
  96. void sonCreator(){
  97. pid_t pid, pid2;
  98. int status1, status2;
  99.  
  100. if(pid = fork() == 0){
  101. counter();
  102. }
  103. else{
  104. if(pid2 = fork() == 0){
  105. counter();
  106. }
  107. else{
  108. //Esperamos a que muera el primer proceso hijo
  109. waitpid(pid, &status1, 0);
  110. //Esperamos a que muera el segundo proceso hijo
  111. waitpid(pid2, &status2, 0);
  112. }
  113. }
  114. std::cout << "Los hijos han finalizado con exito, soy el padre." << std::endl;
  115. }
  116.  
  117. int main(){
  118. sonCreator();
  119.  
  120. return 0;
  121. }
  122.  
  123. ///EJERCICIO 6
  124. //Crea un programa en C++ que pida algo por teclado, lo printe y vuelva a pedir algo por teclado y printe, hasta que se entre por teclado "Exit"
  125. //Crea otro programa que contenga un proceso que cree otros dos procesos hijos. Desde cada uno de los hijos debe llamarse al programa anterior.
  126. //Evita que los procesos queden zombie. Explica como lo has conseguido.
  127.  
  128. int main(){
  129. int status;
  130. pid_t pid1 = fork();
  131. char recoge;
  132. if(pid1 == 0){
  133. while(1){
  134. std::cin >> recoge;
  135. std::cout << "Proceso hijo recoge." << recoge << std::endl;
  136. }
  137. }
  138. else{
  139. while(1){
  140. std::cin >> recoge;
  141. std::cout << "Salta el recoge del padre" << std::endl;
  142. std::cout << "Proceso padre recoge." << recoge << std::endl,
  143. }
  144. }
  145.  
  146. return 0;
  147. }
  148.  
  149. void ControlSalida(int _param){
  150. char c;
  151. std::cout << "Quieres salir del programa? S/n: ";
  152. std::cin >> c;
  153.  
  154. if(c == 'S' || c == 's'){
  155. exit(0);
  156. }
  157. }
  158.  
  159. void ControlAlarma(int _param){
  160. exit(0);
  161. }
  162.  
  163. int main(){
  164. signal(SIGINT, ControlSalida);
  165. signal(SIGALRM, ControlAlarma);
  166. alarm(20);
  167. while(1){
  168. pause();
  169. }
  170. }
  171.  
  172. void Despertando(int _param){
  173. alarm(5);
  174. }
  175.  
  176. void DespiertaTroll(int _param){
  177. std::cout << "Despierta el troll" << std::endl;
  178. }
  179.  
  180. ///EJERCICIO 11
  181. int main(){
  182. pid_t pid = fork();
  183. if(pid == 0){
  184. ///HIJO
  185. std::cout << "Clica tecla para despertar al troll ... ";
  186.  
  187.  
  188. char l;
  189. std::cin >> l;
  190. kill(getppid(), SIGUSR1);
  191. pause();
  192. }
  193. else{
  194. ///PADRE
  195. signal(SIGUSR1, Despertando);
  196. signal(SIGALRM, DespiertaTroll);
  197. while(1) pause();
  198. }
  199. }
  200.  
  201. ///EJERCICIO 12
  202. //
  203. void SignalEntrada(int _param){
  204. alarm(5);
  205. }
  206.  
  207. void SignalDespertar(int _param){
  208. std::cout << "Se ha despertado troll" << std::endl;
  209. }
  210.  
  211. int main() {
  212. std::cout << "Cuantos npc quieres crear?: ";
  213. int counter;
  214. std::cin >> counter;
  215. std::vector<pid_t> pidTrolls;
  216. for(int i = 0; i < counter; ++i){
  217. pid_t pid = fork();
  218. if(pid == 0){
  219. ///PROCESO TROLL
  220. signal(SIGUSR1, SignalEntrada);
  221. signal(SIGALRM, SignalDespertar);
  222.  
  223. while(1) pause();
  224. }
  225. else{
  226. ///PROCESO PADRE
  227. pidTrolls.push_back(pid);
  228. }
  229. }
  230. ///PROCESO PADRE
  231. std::cout << "Despertamos a los trolls?" << std::endl;
  232. char tecla;
  233. std::cin >> tecla;
  234. for(int i = 0; i < pidTrolls.size(); ++i){
  235. kill(pidTrolls[i], SIGUSR1);
  236. }
  237.  
  238. while(1) pause();
  239. return 0;
  240. }
  241.  
  242. ///EJERCICIO 13
  243.  
  244. pid_t pidMove, pidMap;
  245.  
  246. void AvisaAlHijoMapa(int _param){
  247. kill(pidMap, SIGUSR1);
  248. }
  249.  
  250. void MsgCargaMapa(int _param){
  251. std::cout << "Se carga nueva zona del mapa" << std::endl;
  252. }
  253.  
  254. int main(){
  255. if(pidMove = fork() == 0){
  256. ///PROCESO HIJO - MOVIMIENTO
  257. for(int i = 0; i < 5; ++i){
  258. for(int j = 0; j < 5; ++j){
  259. std::cout << "(" << i << "," << j << ")" << std::endl;
  260. sleep(1);
  261. }
  262. kill(getppid(), SIGUSR1);
  263. }
  264. }
  265. else{
  266. ///PROCESO PADRE
  267. if(pidMap = fork() == 0){
  268. ///PROCESO HIJO - MAPA
  269. signal(SIGUSR1, MsgCargaMapa);
  270. while(1) pause();
  271. }
  272. else{
  273. ///PROCESO PADRE
  274. signal(SIGUSR1, AvisaAlHijoMapa);
  275. int status;
  276. wait(&status);
  277. kill(pidMap, SIGKILL);
  278. //while(1) pause();
  279. }
  280. }
  281. ///PROCESO PADRE
  282.  
  283. return 0;
  284.  
  285. }
  286.  
  287. ///1.Cerrar el STD:out
  288. ///2.Abrir un fichero en modo WR
  289. ///3.couts...
  290. ///4.Cerrar este fichero
  291.  
  292. int main(){
  293. int fd_in;
  294.  
  295. close(1);
  296. fd_in = open("/home/juan/Escritorio/hola.txt", O_WRONLY);
  297. if(fd_in < 0){
  298. std::cout << "Error al abrir el fichero Hola.txt" << std::endl;
  299. exit(0);
  300. }
  301.  
  302. std::cout << "Hola chicos." << std::endl;
  303.  
  304. close(fd_in);
  305. return 0;
  306. }
  307.  
  308. int main(){
  309. int estado;
  310. pid_t pidHijo;
  311. int fd[2];
  312. char buffer[512];
  313. char buffer2[512];
  314. char buffer3[512];
  315.  
  316. estado = pipe(fd);
  317. if(estado < 0){
  318. std::cout << "Error al crear la pipe" << std::endl;
  319. }
  320.  
  321. pidHijo = fork();
  322. if(pidHijo == 0){
  323. ///PROCESO HIJO
  324. close(fd[0]);
  325. write(fd[1], "Retrasado", 9);
  326. write(fd[1], "Retrasado2", 10);
  327. write(fd[1], "Retrasado3", 10);
  328. std::cout << "Adios hijo" << std::endl;
  329. }
  330. else{
  331. ///PROCESO PADRE
  332. close(fd[1]);
  333. read(fd[0], buffer, 9);
  334. read(fd[0], buffer2, 10);
  335. read(fd[0], buffer3, 10);
  336. std::cout << buffer << std::endl;
  337. std::cout << buffer2 << std::endl;
  338. std::cout << buffer3 << std::endl;
  339. std::cout << "Hola" << std::endl;
  340. }
  341. }
  342.  
  343. int main(){
  344. int estado;
  345. pid_t pidHijo;
  346. int fd[2];
  347. char buffer[512];
  348.  
  349. estado = pipe(fd);
  350. if(estado < 0){
  351. std::cout << "Error al crear la pipe" << std::endl;
  352. }
  353.  
  354. pidHijo = fork();
  355. if(pidHijo == 0){
  356. ///PROCESO HIJO
  357. write(fd[1], "Hola soy el hijo", 16);
  358. read(fd[0], buffer, 33);
  359. std::cout << buffer << std::endl;
  360. }
  361. else{
  362. ///PROCESO PADRE
  363. write(fd[1], "Hola soy el padre", 17);
  364.  
  365.  
  366. }
  367. }
  368.  
  369. char buffer[512];
  370. int fd[2];
  371.  
  372. void misCojones(int _param){
  373. read(fd[0], buffer, 24);
  374. std::cout << buffer << " recibido en el hijo 1" << std::endl;
  375. }
  376.  
  377. //Ejercicio 20
  378. int main(){
  379. int estado;
  380. pid_t pidHijo1, pidHijo2;
  381. char buffer2[512];
  382.  
  383. estado = pipe(fd);
  384. if(estado < 0){
  385. std::cout << "Error al crear la pipe" << std::endl;
  386. exit(0);
  387. }
  388.  
  389. pidHijo1 = fork();
  390. if(pidHijo1 == 0){
  391. ///HIJO 1
  392. close(fd[1]);
  393. signal(SIGUSR1, misCojones);
  394. pause();
  395. }
  396. else{
  397. pidHijo2 = fork();
  398. if(pidHijo2 == 0){
  399. ///HIJO 2
  400. close(fd[1]);
  401. read(fd[0], buffer2, 24);
  402. std::cout << buffer2 << " recibido en el hijo 2" << std::endl;
  403. }
  404. else{
  405. ///PADRE
  406. close(fd[0]);
  407. write(fd[1], "Te envio esto como padre", 24);
  408. kill(pidHijo1, SIGUSR1);
  409. //write(fd[1], "Te envio esto como padre2", 24);
  410. }
  411. }
  412. }
  413.  
  414. int main(){
  415. int fd_out;
  416.  
  417. close(STDOUT_FILENO);
  418. fd_out = open("/home/juan/Escritorio/hola.txt", O_WRONLY);
  419. if(fd_out < 0){
  420. std::cout << "Error al abrir el fichero Hola.txt" << std::endl;
  421. exit(0);
  422. }
  423.  
  424. std::cout << "Molabas mas cuando eras Crema" << std::endl;
  425.  
  426. close(fd_out);
  427. return 0;
  428. }
  429.  
  430.  
  431.  
  432. //Ejercicio 16 - Parte 2 practica
  433. int main(){
  434. int fdout = open("/home/juan/Escritorio/hola.txt", O_WRONLY);
  435. if(fdout < 0){
  436. exit(0);
  437. }
  438. pid_t pid = fork();
  439. if(pid == 0){
  440. std::string str="Soy el hijo";
  441. write(fdout, str.c_str(), str.size());
  442. close(fdout);
  443. }
  444. else{
  445. int
  446. }
  447. }
  448.  
  449. //Ejercicio 21 - Parte 2 practica
  450. int fdPipe1[2];
  451. int fdPipe2[2];
  452.  
  453. void RecogeDePipe(int _param){
  454. int num;
  455. switch (_param)
  456. {
  457. case SIGUSR1:
  458. read(fdPipe1[0], &num, sizeof(int));
  459. std::cout << "Llega del H1 -->" << std::endl;
  460. break;
  461. case SIGUSR2:
  462. read(fdPipe2[0], &num, sizeof(int));
  463. std::cout << "Llega del H2 -->" << num << std::endl;
  464. break;
  465. default:
  466. break;
  467. }
  468. }
  469.  
  470. int main(){
  471. ///En las pipes la posición 0 es de lectura y la 1 de escritura
  472. int pidHijo1, pidHijo2;
  473. int estado;
  474. size_t lenght = 512;
  475. char buffer[512];
  476.  
  477. estado = pipe(fdPipe1);
  478. if(estado < 0){
  479. std::cout << "Error al crear pipe" << std::endl;
  480. exit(0);
  481. }
  482. estado == pipe(fdPipe2);
  483. if(estado < 0){
  484. std::cout << "Error al crear pipe" << std::endl;
  485. exit(0);
  486. }
  487.  
  488. if(pidHijo1 = fork() == 0){
  489. ///PRIMER HIJO
  490. close(fdPipe1[0]);
  491. close(fdPipe2[0]);
  492. close(fdPipe2[1]);
  493. ///ENVIAR MENSAJES
  494. for(int i = 0; i <= 3; ++i){
  495. write(fdPipe1[1], &i, sizeof(int));
  496. kill(getppid(), SIGUSR1); //El kill no mata al proceso, manda una señarl
  497. sleep(1);
  498. }
  499. }
  500. else{
  501. if(pidHijo2 = fork() == 0){
  502. ///SEGUNDO HIJO
  503. close(fdPipe2[0]);
  504. close(fdPipe1[0]);
  505. close(fdPipe1[1]);
  506. ///ENVIAR MENSAJES
  507. for(int i = 0; i <= 3; ++i){
  508. write(fdPipe2[1], &i, sizeof(int));
  509. kill(getppid(), SIGUSR2); //El kill no mata al proceso, manda una señarl
  510. sleep(1);
  511. }
  512. }
  513. else{
  514. ///PADRE
  515. close(fdPipe1[1]);
  516. close(fdPipe2[1]);
  517. int status;
  518. wait(&status);
  519. wait(&status);
  520. }
  521. }
  522.  
  523. return 0;
  524. }
  525.  
  526. //Ejercicio 21 - Versión Alex
  527.  
  528. pid_t pidHijoUno, pidHijoDos;
  529. int fdUno[2], fdDos[2];
  530.  
  531. void readPipe(int param)
  532. {
  533. int num;
  534.  
  535. if (param == SIGUSR1) {
  536. read(fdUno[0], &num, sizeof(int));
  537. std::cout << num << ", hijo 1\n";
  538. return;
  539. } else if (param == SIGUSR2) {
  540. read(fdDos[0], &num, sizeof(int));
  541. std::cout << num << ", hijo 2\n";
  542. return;
  543. }
  544. }
  545.  
  546. int main()
  547. {
  548. size_t length = 512;
  549. char buffer[512];
  550.  
  551. signal(SIGUSR1, readPipe);
  552. signal(SIGUSR2, readPipe);
  553.  
  554. int estadoUno = pipe(fdUno);
  555. if (estadoUno < 0)
  556. {
  557. std::cout << "Error al crear la pipe\n";
  558. exit(0);
  559. }
  560.  
  561. int estadoDos = pipe(fdDos);
  562. if (estadoDos < 0)
  563. {
  564. std::cout << "Error al crear la pipe\n";
  565. exit(0);
  566. }
  567.  
  568. pidHijoUno = fork();
  569.  
  570. if (pidHijoUno == 0)
  571. { // Hijo 1
  572. close(fdUno[0]);
  573. close(fdDos[0]);
  574. close(fdDos[1]);
  575.  
  576. for (int i = 0; i <= 3; i++)
  577. {
  578. write(fdUno[1], &i, sizeof(int));
  579. kill(getppid(), SIGUSR1);
  580. sleep(1);
  581. }
  582. }
  583. else
  584. { // Proceso padre
  585.  
  586. pidHijoDos = fork();
  587.  
  588. if (pidHijoDos == 0)
  589. { // Hijo 2
  590. close(fdUno[0]);
  591. close(fdUno[1]);
  592. close(fdDos[0]);
  593.  
  594. for (int i = 0; i <= 3; i++)
  595. {
  596. write(fdDos[1], &i, sizeof(int));
  597. kill(getppid(), SIGUSR2);
  598. sleep(1);
  599. }
  600. }
  601. else
  602. { // Padre
  603. close(fdUno[1]);
  604. close(fdDos[1]);
  605.  
  606. // Esperar a los hijoss
  607. int status;
  608. wait(&status);
  609. wait(&status);
  610. }
  611. }
  612. }
  613.  
  614. int main(){
  615. int* p;
  616. int shmID = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT|0666);
  617.  
  618. p = (int)shmat(shmID, NULL, 0);
  619. }
  620.  
  621. ///EJERCICIO 24 - DA FRESH
  622. struct Mapa
  623. {
  624. int x;
  625. int y;
  626. };
  627. Mapa* mapa;
  628.  
  629. void Pintar(int _param){
  630. std::cout << mapa->x << ", " << mapa->y << std::endl;
  631. }
  632.  
  633. int main(){
  634. pid_t pidMoverPlayer;
  635.  
  636. //Reserva del espacio de memoria compartida
  637. int shmID = shmget(IPC_PRIVATE, sizeof(Mapa), IPC_CREAT|0666);
  638. if(shmID < 0){
  639. std::cout << "Fallo al crear espacio de memoria compartida" << std::endl;
  640. exit(0);
  641. }
  642.  
  643. //Vinculamos la memoria
  644. mapa = (Mapa*)shmat(shmID, NULL, 0);
  645. if(mapa < 0){
  646. std::cout << "Fallo al vincular memoria" << std::endl;
  647. exit(0);
  648. }
  649.  
  650. pidMoverPlayer = fork();
  651. if(pidMoverPlayer == 0){
  652. ///PROCESO HIJO QUE MUEVE AL PLAYER
  653. for(int x = 0; x < 5; x++){
  654. mapa->x = x;
  655. for(int y = 0; y < 5; y++){
  656. mapa->y = y;
  657. kill(getppid(), SIGUSR1);
  658. sleep(1);
  659. }
  660. }
  661. }
  662. else{
  663. signal(SIGUSR1, Pintar);
  664. pause();
  665. }
  666.  
  667. int status;
  668. wait(&status);
  669. shmdt(mapa);
  670. shmctl(shmID, IPC_RMID, NULL);
  671. }
  672. int number = 10000;
  673. int* life = &number;
  674.  
  675. int main(){
  676. int pidDest1, pidDest2, pidDest3, pidDest4;
  677.  
  678. int shmID = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT|0666);
  679. if(shmID < 0){
  680. std::cout << "Error al reservar memoria para compartir." << std::endl;
  681. exit(0);
  682. }
  683.  
  684. life = (int*)shmat(shmID, NULL, 0);
  685. if(life < 0){
  686. std::cout << "Error al vincular memoria compartida." << std::endl;
  687. exit(0);
  688. }
  689.  
  690. pidDest1 = fork();
  691. if(pidDest1 == 0){
  692. ///DESTRUCTOR 1
  693. life -= 100;
  694. std::cout << "Acabo de pegarle al edificio 100 - " << *life << std::endl;
  695. }
  696. else{
  697. pidDest2 = fork();
  698. if(pidDest2 == 0){
  699. ///DESTRUCTOR 2
  700. life -= 250;
  701. std::cout << "Acabo de pegarle al edificio 250 - " << *life << std::endl;
  702. }
  703. else
  704. {
  705. pidDest3 = fork();
  706. if(pidDest3 == 0)
  707. {
  708. ///CONSTRUCTOR 1
  709. life += 50;
  710. std::cout << "Acabo de curar al edificio 50 - " << *life << std::endl;
  711. }
  712. else
  713. {
  714. pidDest4 = fork();
  715. if(pidDest4 == 0)
  716. {
  717. ///CONSTRUCTOR 2
  718. life += 25;
  719. std::cout << "Acabo de curar al edificio 25 - " << *life << std::endl;
  720. }
  721. else
  722. {
  723. ///PROCESO PADRE
  724. if(life <= 0)
  725. {
  726. std::cout << "BOOOOOOOOOOOOOOOOOOOOOOOOOOM" << std::endl;
  727. sleep(2);
  728. }
  729. }
  730. }
  731. }
  732. }
  733.  
  734. int status;
  735. wait(&status);
  736. shmdt(life);
  737. shmctl(shmID, IPC_RMID, NULL);
  738. }
  739.  
  740.  
  741. //EJERCICIO 24 y 25 de la parte 3 de prácticas
  742. //#define MAX 512
  743.  
  744. struct MapaDeJuego{
  745. int posX, posY;
  746. };
  747.  
  748. MapaDeJuego* mapa;
  749.  
  750. void Repinta(int _param){
  751. for(int x = 0; x < MAX; x++){
  752. for(int y = 0; y < MAX; y++){
  753. if(x = mapa->posX && y == mapa->posY){
  754. std::cout << "O";
  755. }
  756. else{
  757. std::cout << "#";
  758. }
  759. }
  760. }
  761. }
  762.  
  763. int main(){
  764. struct Datos* p;
  765.  
  766. int shmID = shmget(IPC_PRIVATE, sizeof(MapaDeJuego), IPC_CREAT | 0666);
  767.  
  768. if(p < 0){
  769. std::cout << "Error al reservar memoria" << std::endl;
  770. exit(0);
  771. }
  772.  
  773. mapa = (MapaDeJuego*)shmat(shmID, NULL, 0);
  774. if(mapa < 0){
  775. std::cout << "Error al obetener puntero" << std::endl;
  776. exit(0);
  777. }
  778.  
  779. signal(SIGUSR1, Repinta);
  780. pid_t pidHijo1 = fork();
  781. pid_t pidHijo2;
  782. if(pidHijo1 == 0){
  783. ///PROCESO HIJO --> MUEVE AL PERSONAJE CADA 1 SEG
  784. for(int x = 0; x < MAX; x++){
  785. mapa->posX = x;
  786. for(int y = 0; y < MAX; y++){
  787. mapa->posY = y;
  788. kill(getppid(), SIGUSR1);
  789. sleep(1);
  790. }
  791. }
  792.  
  793. exit(0);
  794. }
  795. else {
  796. ///PROCESO PADRE
  797. pidHijo2 = fork();
  798. if(pidHijo2 == 0){
  799. //PROCESO HIJO 2 --> CREA EXPLOSIONES 2x2 que duran cada 5 segundos
  800.  
  801. }
  802. else{
  803. ///PADRE
  804. shmdt(mapa);
  805. ///LIBERAMOS LA ZONA DE MEMORIA COMPARTIDA --> LOS OTROS PROCESOS NO LA PODRÁN USAR
  806. int status;
  807. wait(&status);
  808. shmdt(mapa);
  809. shmctl(shmID, IPC_RMID, NULL);
  810. }
  811. }
  812.  
  813. ///PROCESO PADRE --> PINTA EL MAPA CUANDO HAY CAMBIOS
  814.  
  815. shmdt(mapa);
  816. ///LIBERAMOS LA ZONA DE MEMORIA COMPARTIDA --> LOS OTROS PROCESOS NO LA PODRÁN USAR
  817. int status;
  818. wait(&status);
  819. shmdt(mapa);
  820. shmctl(shmID, IPC_RMID, NULL);
  821.  
  822. return 0;
  823. }
  824.  
  825. #define MAX 100000
  826.  
  827. void sumaFun(int *numero){
  828. for(int i = 0; i < MAX; i++){
  829. (*numero)++;
  830. }
  831. shmdt(numero);
  832. }
  833.  
  834. int main(){
  835. pid_t pidHijo1, pidHijo2, pidHijo3;
  836.  
  837. //Creamos espacio de memoria compartida.
  838. int shmID = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT|0666);
  839. if(shmID < 0){
  840. std::cout << "Error al crear el espacio de memoria compartida." << std::endl;
  841. }
  842.  
  843. //Vinculamos la variable al espacio de memoria creado antes
  844. int* suma = (int*)shmat(shmID, NULL, 0);
  845. if(suma < 0){
  846. std::cout << "Error al vincular memoria compartida." << std::endl;
  847. }
  848.  
  849. //Creamos los procesos
  850. pidHijo1 = fork();
  851. if(pidHijo1 == 0){
  852. ///PROCESO HIJO 1
  853. sumaFun(suma);
  854. exit(0);
  855. }
  856. else{
  857. pidHijo2 = fork();
  858. if(pidHijo2 == 0){
  859. ///PROCESO HIJO 2
  860. sumaFun(suma);
  861. exit(0);
  862. }
  863. else{
  864. pidHijo3 = fork();
  865. if(pidHijo3 == 0){
  866. ///PROCESO HIJO 3
  867. sumaFun(suma);
  868. exit(0);
  869. }
  870. }
  871. }
  872.  
  873.  
  874.  
  875.  
  876. int status;
  877. wait(&status);
  878. wait(&status);
  879. wait(&status);
  880.  
  881. std::cout << "El resultado final es: " << (*suma) << std::endl;
  882.  
  883. shmdt(suma);
  884. shmctl(shmID, IPC_RMID, NULL);
  885. }
  886.  
  887. ///Ejercicio anterior pero con semaforos
  888. void SemWait(int _semID){
  889. sembuf opSem;
  890. opSem.sem_num = 0;
  891. opSem.sem_op = -1;
  892. opSem.sem_flg = SEM_UNDO;
  893.  
  894. int okOP = semop(_semID, &opSem, 1);
  895. if(okOP < 0){
  896. std::cout << "Error en el waiter" << std::endl;
  897. }
  898. }
  899.  
  900. void semSignal(int _semID){
  901. sembuf opSem;
  902. opSem.sem_num = 0;
  903. opSem.sem_op = 1;
  904. opSem.sem_flg = SEM_UNDO;
  905.  
  906. int okOP = semop(_semID, &opSem, 1);
  907. if(okOP < 0){
  908. std::cout << "Error en el signal" << std::endl;
  909. }
  910. }
  911.  
  912. void sumaFun(int *numero, int _semID){
  913. for(int i = 0; i < MAX; i++){
  914. //Queremos proteger el acceso de los procesos a zona de memoria, para que la suma se realice con éxito
  915. SemWait(_semID);
  916. (*numero)++;
  917. semSignal(_semID);
  918. }
  919. shmdt(numero);
  920. }
  921.  
  922. int main(){
  923. pid_t pidHijo1, pidHijo2, pidHijo3;
  924.  
  925. //Creamos espacio de memoria compartida.
  926. int shmID = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT|0666);
  927. if(shmID < 0){
  928. std::cout << "Error al crear el espacio de memoria compartida." << std::endl;
  929. }
  930.  
  931. //Vinculamos la variable al espacio de memoria creado antes
  932. int* suma = (int*)shmat(shmID, NULL, 0);
  933. if(suma < 0){
  934. std::cout << "Error al vincular memoria compartida." << std::endl;
  935. }
  936.  
  937. //Creamos espacio para la cantidad de semaforos que le pasamos
  938. int semID = semget(IPC_PRIVATE, 1, IPC_CREAT|0600);
  939. if(semID < 0){
  940. std::cout << "Error al reservar memoria para el semaforo" << std::endl;
  941. }
  942.  
  943. int semInit = semctl(semID, 0, SETVAL, 1);
  944. if(semInit < 0){
  945. std::cout << "Error al inicializar el semaforo" << std::endl;
  946. }
  947.  
  948. //Creamos los procesos
  949. pidHijo1 = fork();
  950. if(pidHijo1 == 0){
  951. ///PROCESO HIJO 1
  952. sumaFun(suma, semID);
  953. exit(0);
  954. }
  955. else{
  956. pidHijo2 = fork();
  957. if(pidHijo2 == 0){
  958. ///PROCESO HIJO 2
  959. sumaFun(suma, semID);
  960. exit(0);
  961. }
  962. else{
  963. pidHijo3 = fork();
  964. if(pidHijo3 == 0){
  965. ///PROCESO HIJO 3
  966. sumaFun(suma, semID);
  967. exit(0);
  968. }
  969. }
  970. }
  971.  
  972.  
  973.  
  974.  
  975. int status;
  976. wait(&status);
  977. wait(&status);
  978. wait(&status);
  979.  
  980. std::cout << "El resultado final es: " << (*suma) << std::endl;
  981.  
  982. shmdt(suma);
  983. semctl(semID, 0, IPC_RMID, NULL);
  984. shmctl(shmID, IPC_RMID, NULL);
  985. }
  986.  
  987. ///EJERCICIO 27
  988.  
  989. void SemWait(int _semID){
  990. sembuf opSem;
  991. opSem.sem_num = 0;
  992. opSem.sem_op = -1;
  993. opSem.sem_flg = SEM_UNDO;
  994.  
  995. int okOp = semop(_semID, &opSem, 1);
  996. if(okOp < 0){
  997. std::cout << "Error en wait" << std::endl;
  998. }
  999. }
  1000.  
  1001. void SemSignal(int _semID){
  1002. sembuf opSem;
  1003. opSem.sem_num = 0;
  1004. opSem.sem_op = 1;
  1005. opSem.sem_flg = SEM_UNDO;
  1006. semop(_semID, &opSem, 1);
  1007. }
  1008.  
  1009. void suma(int* _numero, int _semID){
  1010. const int MAX = 1000000;
  1011. for(int i = 0; i < MAX; i++){
  1012. ///ZONA CRITICA
  1013.  
  1014. ///PROTEGER LA VARIABLE
  1015. SemWait(_semID);
  1016. (*_numero)++;
  1017. ///DESPROTEGER LA ZONA -- signal
  1018. SemSignal(_semID);
  1019. }
  1020. shmdt(_numero);
  1021. }
  1022.  
  1023. int main(){
  1024. int pidProc1, pidProc2, pidProc3;
  1025.  
  1026. int shmID = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666);
  1027. if(shmID < 0){
  1028. std::cout << "No se ha podido reservar memoria." << std::endl;
  1029. }
  1030.  
  1031. int* numero = (int*)shmat(shmID, NULL, 0);
  1032.  
  1033. int semID = semget(IPC_PRIVATE, 1, IPC_CREAT | 0666);
  1034. if(semID < 0){
  1035. std::cout << "Error al reservar la memoria del semaforo." << std::endl;
  1036. exit(0);
  1037. }
  1038.  
  1039. int semInit = semctl(semID, 0, SETVAL, 1);
  1040. if(semInit < 0){
  1041. std::cout << "Error al inicializar el semaforo." << std::endl;
  1042. exit(0);
  1043. }
  1044.  
  1045. pidProc1 = fork();
  1046. if(pidProc1 == 0){
  1047. suma(numero, semID);
  1048. exit(0);
  1049. }
  1050. else{
  1051. pidProc2 = fork();
  1052. if(pidProc2 == 0){
  1053. suma(numero, semID);
  1054. exit(0);
  1055. }
  1056. else{
  1057. pidProc3 = fork();
  1058. if(pidProc3 == 0){
  1059. suma(numero, semID);
  1060. exit(0);
  1061. }
  1062. }
  1063. }
  1064.  
  1065. int status;
  1066. wait(&status);
  1067. wait(&status);
  1068. wait(&status);
  1069.  
  1070. std::cout << "El resultado de la suma es: " << (*numero) << std::endl;
  1071. shmdt(numero);
  1072. shmctl((shmID), IPC_RMID, NULL);
  1073. semctl(semID, 0, IPC_RMID, NULL);
  1074. return 0;
  1075. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement