i need to create a process tree using fork() in linux.
The tree must be like that :
Moreover, each process has a random ID. So in each process, we must compare his ID and his son(s) ID(s) and keep the minimal ID.
So, i've tried to do the left part of the tree with a recursive function but it doesn't work... (many issues with pipes...)
(i'm sorry, my English is bad because i'm French :( )
int creerArbreGauche(int n,int m)
{
if(m>0){
if(fork()==0){
printf("pid : %d m : %d \n",getpid(),m);
if(m==(n-1)) //si on est au dernier proc
{
printf("Premiere condition %d \n",id[0][m]);
close(tube_G_FP[0]);
write(tube_G_FP[1],&id[0][m],sizeof(int));
creerArbreGauche(n,m-1);
//read(tube_G_FP[0],&var,sizeof(int));
}
else{
printf("Je rentre ici\n");
close(tube_G_FP[1]);
read(tube_G_FP[0],&var,sizeof(int));
printf("Var = %d\n",var);
if(var<id[0][m]){
close(tube_G_FP[0]);
write(tube_G_FP[1],&var,sizeof(int));
printf("Var gagne et l'envoie au pere: %d \n",var);
creerArbreGauche(n,m-1);
//close(tube_G_FP[1]);
}
else{
close(tube_G_FP[0]);
write(tube_G_FP[1],&id[0][m],sizeof(int));
printf("id[0][%d] gagne et envoie au pere son id : %d \n",m,id[0][m]);
creerArbreGauche(n,m-1);
}
}
exit(0);
}
wait(NULL);
}
else{
return 0;
}
}
This is clearly wrong:
close(tube_G_FP[1]); // we close tube_G_FP[1]
read(tube_G_FP[0],&var,sizeof(int));
printf("Var = %d\n",var);
if(var<id[0][m]){
close(tube_G_FP[0]);
write(tube_G_FP[1],&var,sizeof(int)); // we write to tube_G_FP[1]
I've found a solution and made this in a single function here it is:
//some of these variables can be declared in the main function
int var;
int var2;
int **id; //tableau d'id
int count;
int creerArbreGauche(int n,int m,int** tab_tube_G,int** tab_tube_D)
{
printf("m : %d\n",m);
if(m>0){
if(fork()==0){
if(m==(n-1)) //si on est au dernier proc
{
printf("Premiere condition, processus : [%d][%d] avec id : %d \n",count,m,id[count][m]);
write(tab_tube_G[m][1],&id[count ][m],sizeof(int));
creerArbreGauche(n,m-1,tab_tube_G,tab_tube_D);
}
else{
printf("Je rentre ici\n");
read(tab_tube_G[m+1][0],&var,sizeof(int));
printf("Var = %d\n",var);
if(var<id[count][m]){
write(tab_tube_G[m][1],&var,sizeof(int));
printf("Var gagne et l'envoie au pere: %d \n",var);
creerArbreGauche(n,m-1,tab_tube_G,tab_tube_D);
}
else{
write(tab_tube_G[m][1],&id[count][m],sizeof(int));
printf("id[%d][%d] gagne et envoie au pere son id : %d \n", count, m, id[count][m]);
creerArbreGauche(n,m-1,tab_tube_G,tab_tube_D);
}
}
exit(0);
}
wait(NULL);
}
else{
if(n==1){
if(fork()==0){
write(tab_tube_D[count][1],&id[count][m],sizeof(int));
printf("on est au processus [%d] [%d]\n",count,m);
exit(0);
}
wait(NULL);
}
else{ //on est dans le vrai pere
printf("On est dans le pere des peres\n");
read(tab_tube_G[m+1][0],&var,sizeof(int));
close(tab_tube_D[count+1][1]);
read(tab_tube_D[count+1][0],&var2,sizeof(int));
printf("id processus [%d][0] : %d \n",(count+1),var2);
printf("VarFinal = %d\n",var);
printf("id du padré %d\n",id[count][m]);
if((var<=id[count][m])&&(var<=var2)){
printf("Var a gagné : %d \n",var);
write(tab_tube_D[count][1],&var,sizeof(int));
return var;
}
else if((var2<=id[count][m])&&(var2<=var)){
printf("Var2 a gagné : %d \n",var2);
write(tab_tube_D[count][1],&var2,sizeof(int));
return var2;
}
else{
printf("id[%d][%d] (Racine) gagne : %d \n", count, m, id[count][m]);
write(tab_tube_D[count][1],&id[count][m],sizeof(int));
return id[count][0];
}
}
}
printf("\n");
}
int main(){
srand(time(NULL));
int n=4, m=n-1;
int i,j;
int res;
//GENERATION DES IDs
id = (int**)malloc(n*sizeof(int*)); //tableau 2D de n ligne id
for(i=0;i<n;i++){
id[i] = (int*)malloc((n-1)*sizeof(int));
}
for(i=0;i<n;i++){
for(j=0;j<(n-i);j++){
id[i][j] = rand()%(n*n);
printf("ceci est l'id : [%d][%d] = %d \n",i,j,id[i][j]);
}
}
//GENERATION DE MES TUBES GAUCHE
int** tab_tube_G =(int**)malloc(n*sizeof(int));
for(int i=0;i<n;i++){
tab_tube_G[i] =(int*)malloc(2*sizeof(int));
pipe(&tab_tube_G[i][0]);
}
//GENERATION DE TUBES DROIT
int** tab_tube_D =(int**)malloc(n*sizeof(int));
for(int i=0;i<n;i++){
tab_tube_D[i] =(int*)malloc(2*sizeof(int));
pipe(&tab_tube_D[i][0]);
}
count = n-1;
//GENERATION COMPLETE DE TOUT MON ARBRE
for(i=1; i<=n; i++){
m=i-1;
printf(" i = %d \t\n",i);
res = creerArbreGauche(i, m, tab_tube_G, tab_tube_D);
count--;
}
printf("res : %d\n",res);
return 0;
}
Related
I don't know why mat[7][8]='A' prints A in the whole column. The procedure is a game grid where we should put pions of gamers and maintain all their previous pions on the grid. I don't know why changing the value of this matrix outside a for loop doesn't do anything right as it supposed to be.
Here is the code:
#include "Go_1.h"
#define DIMENSION 9
#define SPACELEFT 2
/* cette donction permet d'affichier la matrice à l'état initial, de placer le pion du joueur à
l'intersection en analysant si la place est vide ou pas, et d'afficher la grille avec les pions
des joueurs*/
void grille(char mat[][TAILLE_MATRICE], int *x, int *y,char jeton,char *joueur,char lettres[],char nombres[])
{
int a=0; /* servira de compteur pour afficher tous les caracteres de A--I en utilsant le code ASCII*/
int b=1;
const int LIGNE_COLONNE=(SPACELEFT-1)*(DIMENSION-1)+ DIMENSION;/* = 25// nb de lignes et colonnes où
on doir afficher les valeurs de la matrice stockées dans LIGNE_COLONNE(25) lignes et colonnes*/
printf("\t");
printf(" "); /*2 spaces*/
/*affichage des lettres délimitant le goban horizontalement*/
for(int j=0;j<DIMENSION;j++)
{
printf("%c", 'A'+a);
a++;
for (int k=0; k<(2*SPACELEFT-1);k++)
{
printf(" "); /*5 spaces 5= 2*SPACELEFT-1 */
}
}
printf("\n");
/*Remplissage de la matrice*/
for (int i=0;i<LIGNE_COLONNE;i+=SPACELEFT)
{
for (int j=0;j<LIGNE_COLONNE;j+=SPACELEFT)
{
mat[i][j]='0';
}
}
mat[7][8]='A';
/*affichage des nombres délimitant le goban verticalement*/
for (int i=0;i<LIGNE_COLONNE;i++) /* LIGNE_COLONNE in this case= 25*/
{
printf("\t");
if (i%SPACELEFT==0)
{
printf("%d ",b);
b++;
}
else
printf(" ");
for (int j=0; j<LIGNE_COLONNE;j++)
{
if ((i%SPACELEFT==0)&&(j%SPACELEFT==0)) /* le cas où mat[i][j] est une intersection*/
{
/*if (i==*x && j==*y) /*tester si les indices coincident avec ceux choisis par le joueur
{
if (mat[*x][*y]=='0') /*tester si l'intersection ets vide cad contient '0'*
{
mat[*x][*y]=jeton;
}
else
{
printf("\tLa place est deja occupee!");
choix_pion(joueur,jeton,x,y,lettres,nombres);/*on lui demande de réexprimer
son choix où placer son pion
break;
}
} */
printf("%c ",mat[i][j]);
}
else if ((i%SPACELEFT==0)&&(j%SPACELEFT!=0))
printf("* ");
else if ((i%SPACELEFT!=0)&&(j%SPACELEFT!=0))
printf(" ");
else if ((i%SPACELEFT!=0)&&(j%SPACELEFT==0))
printf("* ");
}
printf("\n");
}
return;
}
Well, I refactored the code a bit and I get the following output:
A B C D E F G H I
Since I did not know how to define TAILLE_MATRICE I just assigned 64
That's the code for anyone wanting to try it out:
#include<stdio.h>
#define DIMENSION 9
#define SPACELEFT 2
#define TAILLE_MATRICE 64
int main(char mat[][TAILLE_MATRICE], int *x, int *y,char jeton,char
*joueur,char lettres[],char nombres[])
{
int a=0;
int b=1;
const int LIGNE_COLONNE=(SPACELEFT-1)*(DIMENSION-1)+ DIMENSION;
printf("\t");
printf(" ");
for(int j=0;j<DIMENSION;j++)
{
printf("%c", 'A'+a);
a++;
for (int k=0; k<(2*SPACELEFT-1);k++)
{
printf(" "); /*5 spaces 5= 2*SPACELEFT-1 */
}
}
printf("\n");
for (int i=0;i<LIGNE_COLONNE;i+=SPACELEFT)
{
for (int j=0;j<LIGNE_COLONNE;j+=SPACELEFT)
{
mat[i][j]='0';
}
}
mat[7][8]='A';
for (int i=0;i<LIGNE_COLONNE;i++)
{
printf("\t");
if (i%SPACELEFT==0)
{
printf("%d ",b);
b++;
}
else
printf(" ");
for (int j=0; j<LIGNE_COLONNE;j++)
{
if ((i%SPACELEFT==0)&&(j%SPACELEFT==0))
{
printf("%c ",mat[i][j]);
}
else if ((i%SPACELEFT==0)&&(j%SPACELEFT!=0))
printf("* ");
else if ((i%SPACELEFT!=0)&&(j%SPACELEFT!=0))
printf(" ");
else if ((i%SPACELEFT!=0)&&(j%SPACELEFT==0))
printf("* ");
}
printf("\n");
}
return 0;
}
i have a function, it write in file but when i update my file, i can see the line i have updated erase the first char of the next line. I saw thiw proceed when the number is >= 10...
`
void addPieceToFile(Piece* p, char* file){
FILE* f = fopen(file, "rw+");
int nbrSalles = 0;
int id = 0;
int test;
if(f != NULL) {
fseek(f,0, SEEK_END);
if(ftell(f) == 0){ //Premier passage ici si le fichier est vide
fprintf(f,"{%d}\n",nbrSalles += 1);
fprintf(f,"[%d|%d]%d\n",p->height, p->width, p->id);
for(int i = 0; i < p->height; i +=1 ){
for(int j = 0; j < p->width; j +=1 ){
fprintf(f,"%c ",p->piece[i][j]);
}
fprintf(f,"\n");
}
}else{ //Si le fichier contient déja une ou plusieur pieces on rentre ici
rewind(f); // On remonte au début du fichier
fscanf(f,"{%d}\n",&nbrSalles); // On récupère le nombre de salles
fscanf(f,"[%d|%d]%d\n",&p->height, &p->width, &id); // On récupère le nombre de salles
fseek(f,0,SEEK_END); // On revient a la fin du fichier ppour ecrire la nouvelle salle
test = testeChaine(TEMP_FILE,file);
if(test==1){
fprintf(f,"[%d|%d]%d\n",p->height, p->width, p->id); // On garde l'id actuelle en cas de modification
}else{
fprintf(f,"[%d|%d]%d\n",p->height, p->width, p->id+nbrSalles); // On met à jour l'id
}
for(int i = 0; i < p->height; i +=1 ){
for(int j = 0; j < p->width; j +=1 ){
fprintf(f,"%c ",p->piece[i][j]);
}
fprintf(f,"\n");
}
rewind(f); // On revient en haut du fichier
nbrSalles = nbrSalles + 1;
fprintf(f,"{%d}",nbrSalles); // Et on met à jour le nombre de salles I THINK THE PROBLEM IS HERE
}
system("clear");
result("Piece ajoutée.");
}else{
system("clear");
printf("Error. %s\n",file);
}
fclose(f);
}
`
I want to avoid this bug.
Thank you for your help.
So, I've made this code, and it works wonderfully, but the problem is that I've got some scanf functions only accepting numbers, and some others only accepting characters, but for example, when I input a character on a scanf that requires an int value, the program behaves really unexpectedly, doing stuff such as repeating the same printf all over the command prompt, or repeating it thrice.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int descuento(int num, int descuento);
int rangoValido(int Rangomin, int Rangomax, int i);
int numeroRandom();
int sino(char sino);
int main(void){
int productoid[1000][1];
int idprompt;
int descuento25[14] = {398, 309, 281, 948, 19, 67, 187, 80, 889, 482, 566, 24, 87, 98};
int descuento15[14] = {992, 788, 987, 90, 155, 596, 27, 587, 98, 273, 344, 69, 89, 234};
char respuesta;
int listacompra[100][1];
int precio;
int colector = 0;
int comprobante = 0;
int total;
int monto;
//Si la id del producto no esta dentro del rango valido, el bloque se repite
do{
do{
do{
printf("Escriba la ID del producto: ");
scanf("%d", &idprompt);
}
while(0==rangoValido(1,1000,idprompt));
//Una vez comprobada la validez del numero ingresado, se crea un numero aleatorio que se le
asigna para el precio, idprompt es la misma id
comprobante = 0;
srand(idprompt);
productoid[idprompt][1]=numeroRandom();
printf("ID del producto: %d\n", idprompt);
printf("Precio del producto: %d\n", productoid[idprompt][1]);
precio = productoid[idprompt][1];
//Comprobacion de descuentos
for(int i=0; i<=14; i++){
if(descuento25[i]==idprompt){
productoid[idprompt][1] = descuento(productoid[idprompt][1],25);
printf("Descuento del producto: 25\n");
}else{
if(descuento15[i]==idprompt){
productoid[idprompt][1] = descuento(productoid[idprompt][1],15);
printf("Descuento del producto: 15\n");
}
}
}
//Anadiendo el producto al carro de compras y comprobando la respuesta
do{
printf("Quieres anadir este producto a tu carrito de compras? (Y/N) ");
scanf(" %c", &respuesta);
}while(2 == sino(respuesta));
}while(respuesta == 'n' || respuesta == 'N');
if(respuesta == 'y' || respuesta == 'Y'){
listacompra[colector][0] = idprompt;
listacompra[colector][1] = precio;
colector = colector + 1;
}
do{
printf("Quieres seguir comprando? (Y/N) ");
scanf(" %c", &respuesta);
printf("\n");
if(0 == sino(respuesta)){
for(int i=0; i<colector; i++){
printf("\nID del producto %d: %d\n", i+1, listacompra[i][0]);
printf("Precio del producto %d: %d\n", i+1, listacompra[i][1]);
}
}
if(1==sino(respuesta)){
comprobante = 1;
}
}while(2==sino(respuesta));
}while(comprobante==1);
for(int i=0; i<colector; i++){
total = total + listacompra[i][1];
}
printf("\n\nTotal a pagar: %d\n", total);
printf("Ingrese monto recibido: ");
scanf("%d", &monto);
printf("\n");
if(monto<total){
printf("%d faltantes.", total-monto);
}
if(monto>=total){
printf("Vuelto: %d", monto-total);
}
return 0;
}
int numeroRandom(){
int random;
random = rand();
if(random>3000 && random<10000){
random = random / 5;
}
if(random<100){
random = random * 3;
}
if(random>10000){
random = random / 13;
}
return random;
}
int rangoValido(int Rangomin, int Rangomax, int i){
if(i>=Rangomin && i<=Rangomax){
return 1;
}else{return 0;}
}
int descuento(int num, int descuento){
num = num * (descuento / 100);
return num;
}
//Si la funcion sino() regresa 0, entonces la respuesta fue no. Si es 1, la respuesta es si. Y si
es 2, la respuesta es invalida.
int sino(char sino){
if(sino=='y' || sino=='Y'){
return 1;
}
if(sino=='n' || sino=='N'){
return 0;
}
else{return 2;}
}
I have this code (Sorry the spanish)
In the "perm()" function, if i use array, to put whatever is in "a", in the array, the console throw me segmentation failed, but when i only print "a", i don't have any issue, so i don't know how to use an array to save the permutations and then print it, not just print it in the function
`
/*
Cree un programa en C el cual solicite a un usuario una palabra de largo n (4 ó 5).
El programa debe generar todas las permutaciones de sus letras, por ejemplo, si el usuario ingresa
la palabra GATO, el programa deberá almacenar en una matriz y posteriormente mostrar las
siguientes combinaciones de letras
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//Funcion Factorial
int fact(int n){
int i, mult;
i=n;
mult=1;
if (n==0){
mult=1;
}
else{
while (i>0){
mult=mult*i;
i=i-1;
}
}
return mult;
}
//Funcion Intercambiar
void cambio(char *a, char *b){
char aux;
aux=*a;
*a=*b;
*b=aux;
}
//Funcion Permutar
char **matriz;
int m=0;
void perm(char *a, int i, int n){
int j;
if (i==n){
matriz[m]=a; //With this i have a problem
printf("%s\n", a);
m=m+1;
}
else{
j=i;
while (j<=n){
cambio((a+i), (a+j));
perm(a, i+1, n);
cambio((a+i), (a+j));
j=j+1;
}
}
}
//Funcion principal
int main(){
/* Pedirle la palabra al usuario y calcular el largo de esta */
char *palabra;
printf("Ingrese una palabra: ");
scanf("%s", palabra); //Tengo la palabra
int largo=0;
while (palabra[largo]){
largo=largo+1; //Tengo largo de la palabra
}
/* Pasar la palabra a un arreglo dinámico */
char *letras=(char*)malloc(sizeof(char*)*largo);
int i=0;
while (i<largo){
letras[i]=palabra[i];
i=i+1;
}
/* Sacar la cantidad de permutaciones */
int nper;
nper=fact(largo); //Tengo la cantidad de permutaciones
/* Armar la matriz */
char **matriz=(char**)malloc(sizeof(char*)*nper);
i=0;
while (i<nper){
matriz[i]=(char*)malloc(sizeof(char)*largo);
i=i+1;
}
/* Permutar(??) */
perm(letras, 0, largo-1);
/*Imprimir Permutaciones*/
i=0;
printf("Las %d permutaciones son\n", nper);
printf("%d\n", m);
printf("%c\n", letras[2]);
while (i<nper){
printf("%s", matriz[i]);
i=i+1;
}
/* Liberar memoria */
i=0;
while (i<nper){
free(matriz[i]);
i=i+1;
}
free(matriz);
free(letras);
return 0;
}
i made a program to calculate multiples of 5 between two numbers, when ask for de second numbers the program didn't work normally.
#include <stdio.h>
int main()
{
int A, B, cont;
printf("\n");
printf("Indique el dominio de los numeros en los que desa saber cuales son multiplos de 5\n");
printf("Primer numero: \n");
scanf("%i",&A);
printf("Segundo numero: \n");
scanf("%i",&B);
if (A < B){
A = B;
//B = A;
}
system("cls");
printf("\n");
printf("Los multiplos de 5 comprendidos entre %i y %i son; \n",A,B);
cont = 0;
while(A < B){
if (A % 5 == 0)
cont++;
A++;
}
if (cont > 0)
printf("Entre los numeros %i y %i hay un total de %i multiplos de 5.\n",A,B,cont);
else
printf("El intervalo no se encuentran multiplos de 5.\n");
getchar();
return 0;
}
You have the format backwards
scanf("i%",&A);
should be
scanf("%i",&A);
Your swapping logic is wrong. Use another variable to do it correctly.
int t = A;
A = B;
B = t;
Also you would want to swap when A is greater than B.
if( A > B ){
/* swap*/
}
#include <stdio.h>
int main()
{
int A, B, cont=0;
printf("Program to find the Multiples of 5\n");
printf("First Number \n");
scanf("%d",&A);
printf("Second Number \n");
scanf("%d",&B);
system("cls");
printf("The Multiples of 5 between %d and %d \n", A,B);
if(A<B){
while(A <= B){
if (A % 5 == 0)
{
cont++;
}
A++;
}
}
else
{
while(A >=B){
if (A % 5 == 0)
{
cont++;
}
A--;
}
}
if (cont > 0)
printf("The total Multiples of 5 between %d and %d are %d\n",A,B,cont);
else
printf("No Multiple of 5 exists between %d and %d\n",A,B);
getchar();
return 0;
}
I try to solve each case. If user enter A>B then your code fails but it works