ProvaPratica 2012.07.17

From Sistemi Operativi
Revision as of 16:02, 20 May 2014 by Coci (talk | contribs)
Jump to navigation Jump to search
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#define BUF_SIZE 20

int main(int argc, char** argv){
	int ncopie, i, ris;
	char command[BUF_SIZE];
	if (argc<3) {printf("inserisci due o più argomenti (ncopie, command)\n"); exit(1);}
	ncopie = atoi(argv[1]);
	strcpy(command, argv[2]);
	for (i = 0; i<ncopie; i++){
		if(fork()){//processo padre
		}
		else {
			char *env_el;
			env_el = malloc(BUF_SIZE);
			sprintf(env_el, "NCOPIA=%d", i);
			//asprintf 
			//devo aggiungerci in fondo lo zero terminatore
			char *newenviron[] = {env_el, (char*) 0};
			//argv+2 sono gli argomenti, ovvero tutti gli argomenti passati dopo il secondo			
			ris = execve(argv[2], argv+2, newenviron);
			if (ris == -1) {perror("execve"); exit(1);}
		}
	}
	for (i = 0; i<ncopie; i++) wait(NULL);
	return 1;
}

Alessandro

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#define BUF_SIZE 20

int main(int argc, char** argv){
				int ncopie, i, ris;
				char command[BUF_SIZE];
				if (argc<3) {printf("inserisci due argomenti (ncopie, command)\n"); exit(1);}
				ncopie = atoi(argv[1]);
				int fd[ncopie];
				pid_t pid[ncopie];
				for (i = 0; i<ncopie; i++){
								char *tmpfile;
								asprintf(&tmpfile,"/tmp/ncopie.%d.%d",getpid(),i);
								fd[i]=open(tmpfile,O_CREAT|O_RDWR,0600);
								unlink(tmpfile);
								if((pid[i]=fork())==0){//processo padre
												char *NCOPIA;
												asprintf(&NCOPIA, "NCOPIA=%d", i); 
												char *newenviron[] = { NCOPIA, (void *)0};	
												dup2(fd[i],STDOUT_FILENO);
												ris = execve(argv[2], argv+2, newenviron);
												if (ris == -1) {perror("execve"); exit(1);}
								}
				}
				for (i = 0; i<ncopie; i++) {
								waitpid(pid[i],NULL,0);
								lseek(fd[i],SEEK_SET,0);
								char *buf[1024];
								int n;
								while ((n=read(fd[i],buf,1024))>0)
												write(STDOUT_FILENO,buf,n);
				}

				return 1;
}