C & C++/C

[C language] 시스템 프로그래밍 작성

Razelo 2021. 11. 8. 10:07

2주차 

code3-1

#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>
int main(){
	int filedes;
	char fname[] = "afile";

	if((filedes = open(fname, O_RDWR)) == -1){
		printf("%s cannot be opened. \n", fname);
	}
	close(filedes);
	return 0; 
}

code3-2

#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>

#define PERMS 0644

char *filename = "newfile";
void main(){
	int fd;

	if((fd = open(filename, O_RDWR | O_CREAT, PERMS)) == -1){
		printf("Cannot create %s \n", filename);
		exit(1);
	}
	exit(0);
}

code3-3

#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>

#define BUFSIZE 512

void main(){
        char buffer[BUFSIZE];
        int fd;
        ssize_t nread;
        long total = 0;

        if((fd = open("testfile", O_RDONLY)) == -1){
                exit(1);
        }
        while((nread = read(fd, buffer, BUFSIZE)) > 0){
                total += nread;
        }

        close(fd);

        printf("Number of characters in testfile: %ld\n", total);
        exit(0);
}

code3-4

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

int main(){
	if((write(1, "Welcome to System Programming", 27)) != 27){
		write(2, "A write error has occurred on file descriptor 1 \n", 47);
	}
	exit(0);
}

lab-1

#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>

#define BUFSIZE 512

int main(int argc, char *argv[]){

	char buffer[BUFSIZE];
	char *fname1 = argv[1];
	char *fname2 = argv[2];
      
	int fd1;
	int fd2; 
	int nread; 

        if((fd1 = open(fname1, O_RDONLY)) == -1){ // readonly open 
                printf("open %s\n", fname1);
		exit(1);
        }
	//creat(fname2, O_RDWR|O_APPEND); // create file bfile 
	if((fd2 = open(fname2, O_RDWR|O_APPEND)) == -1){   // read and write 
		printf("open %s\n", fname2);
		exit(1);
	}

	printf("start copying \n");
	while((nread = read(fd1, buffer, BUFSIZE)) > 0){ 
		printf("\n\n%d\n\n",nread);
		write(fd2, buffer, nread);
	}

	printf("finish\n"); 
        close(fd1);
	close(fd2); 
        exit(0);
}

 


3주차

 code3-5

#include<stdio.h>
#include<unistd.h>
int main(){
	if(lseek(STDIN_FILENO, 0, SEEK_CUR) == -1)
		printf("cannot seek \n");
	else
		printf("seek OK \n");
	return 0; 
}

code3-6

#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<error.h>

char buf1[] = "abcdefghij";
char buf2[] = "ABCDEFGHIJ";

int main(){
        int fd;

        if((fd = creat("file.hole", S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0)
                perror("file.hole");

        if(write(fd, buf1, 10) != 10)
                perror("buf1");

        if(lseek(fd, 40, SEEK_SET) == -1)
                perror("lseek");

        if(write(fd, buf2, 10) != 10)
                perror("buf2");

        return 0;
}

code3-7

#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<string.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>
#define BUFFSIZE 512
#define FILESIZE (100 * 100 * 1024)
#define COUNT FILESIZE / BUFFSIZE

void main(){
        int i, fd;
        char buf[BUFFSIZE];

        memset(buf, '.', BUFFSIZE);
        if((fd = creat("file.write", S_IRUSR | S_IWUSR)) < 0)
                exit(1);
        for(i = 0; i < COUNT; ++i)
                write(fd, buf, BUFFSIZE);

        close(fd);
        exit(0);
}

code3-8

#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<error.h>
int main(){
	int fd;

	if((fd = creat("afile", S_IRUSR | S_IWUSR)) == -1)
		perror("afile");
	printf("This is displayed on the screen. \n");
	close(STDOUT_FILENO);
	dup(fd);
	close(fd);
	printf("This is written into the redirected file. \n");
	return 0; 
}

code3-9

#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<error.h>
int main(){
	int fd;

	if((fd = creat("afile", S_IRUSR | S_IWUSR)) == -1)
		perror("afile");
	printf("This is displayed on the screen. \n");
	dup2(fd, STDOUT_FILENO); // TO 1 
	close(fd);
	printf("This is written into the redirected file. \n");
	return 0; 
}

code3-10

#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/stat.h>
#include<error.h>

int main(int argc, char* argv[]){

	if(argc != 2)
		printf("usage: a.out <pathname>");
	
	if(access(argv[1], R_OK) < 0)
		perror("R_OK");
	else
		printf("read acess OK \n");
	
	if(open(argv[1], O_RDONLY) < 0)
		perror("O_RDONLY");
	else
		printf("open for reading OK \n");

	return 0; 	
}

lab-2

#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>

#define BUF_SIZE 64

int main(){

        char *filename = "test.txt";
        char *buf1 = "abcdefghijklmnop";
        char buffer[BUF_SIZE];
	
	int fd;
	int nread;

        fd = open(filename, O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR);
        if(write(fd, buf1, 16) == -1)
                exit(1);

        if(lseek(fd, 10, SEEK_SET) == -1)
               exit(1);

        while(nread = read(fd, buffer, BUF_SIZE) > 0)
                printf("%s\n", buffer);
	
	memset(buffer, 0, BUF_SIZE); // initial 

        if(lseek(fd, -5, SEEK_END) == -1)
                exit(1);

        while(nread = read(fd, buffer, BUF_SIZE) > 0)
                printf("%s\n", buffer);
                
        return 0;       
}

lab-3

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#include<time.h>
int main(){
        struct stat buf;

        int fd;

        fd = creat("testfile", S_IRUSR | S_IWUSR);
        stat("testfile", &buf);

	printf("file inode: %ld\n", (long)buf.st_ino);            //  i - node
	printf("file first created: %s", ctime(&buf.st_ctime)); // status change time
	printf("file last updated: %s", ctime(&buf.st_mtime));  // change time 
	printf("file last accessed: %s", ctime(&buf.st_atime)); // access time 

	return 0;
}

lab-4

#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
int main(int argc, char *argv[]){

        char buf[20];
        int fd;

        if(access(argv[1], F_OK)  == 0){
		if((fd = open(argv[1], O_RDWR, S_IRUSR | S_IWUSR)) == -1)
			exit(1);

                if(read(fd, buf, 20) == -1)
                        exit(1);

                if(write(1, buf, 20) == -1) // print to stdout -> monitor
                       exit(1);

                printf("\n");
        }
        else{
		if((fd = creat(argv[1], S_IRUSR | S_IWUSR)) == -1)
		       exit(1);
                if(write(fd, "hello world", 11) == -1)
                        exit(1);
        }

        return 0;
}

 


4주차

code4-1

#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>
#include "error.h"
int main(){
	int fd, len;
	char buf[20];

	fd = open("tempfile", O_RDWR | O_CREAT | O_TRUNC, 0666);
	if(fd == -1) perror("open1");
	unlink("tempfile");
	len = write(fd, "How are you?", 12);
	if(len != 12) perror("write");
	lseek(fd, 0L, SEEK_SET);
	len = read(fd, buf, sizeof(buf));
	if(len < 0) perror("read");
	buf[len] = '\0';
	printf("%s\n", buf);
	close(fd);
	fd = open("tempfile", O_RDWR);
	if(fd == -1) perror("open2");
	close(fd);
	return 0; 
}

lab-5

#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include "error.h"
int main(int argc, char* argv[]){ // ./a.out <original file> <new file>
	int fd;
	int l; 
	fd = open(argv[1], O_RDWR, 0666);
	if (fd == -1) perror("cannot open this file");
	l = link(argv[1], argv[2]);
	unlink(argv[1]);
	if (l == -1) perror("link error has been occured \n");
	close(fd);
	return 0; 
}

5주차

code4-2

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include "error.h"
int main(void){

	umask(0);
	if(creat("foo", S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH) < 0)
		perror("foo");

	umask(S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
	if(creat("bar", S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH) < 0)
		perror("bar");
	return 0; 
}

code4-3

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include "error.h"
int main(){
	struct stat statbuf;

	if(stat("foo", &statbuf) < 0)
		perror("stat(foo)");
	if(chmod("foo", (statbuf.st_mode & ~S_IXGRP) | S_ISGID) < 0)
		perror("chmod(foo)");

	if(chmod("bar", S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0)
		perror("chmod(bar)");

	return 0;
}

code4-4

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<utime.h>
#include "error.h"
int main(int argc, char* argv[]){
	int i;
	struct stat statbuf;
	struct utimbuf timebuf;

	for(i = 1; i < argc; i++){ //begin with index 1 -> ./a.out is index 0 , and fileanme is index 1
		if(stat(argv[i], &statbuf) < 0)
			perror(argv[i]);

		if(open(argv[i], O_RDWR | O_TRUNC) < 0)
			perror(argv[i]);

		timebuf.actime = statbuf.st_atime;
		timebuf.modtime = statbuf.st_mtime;
		if(utime(argv[i], &timebuf) < 0)
			perror(argv[i]);
	}
	return 0;
}

code4-5

#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<string.h>
#include<sys/stat.h>
#include<dirent.h>

#include "error.h"
typedef struct dirent Dirent;

int main(int argc, char* argv[]){
	Dirent *dp;
	DIR *dir_fd;

	while(--argc > 0){
		if(!(dir_fd = opendir(*++argv))){ //opendir returns null if fail, ++argv means ./a.out will  excepted 
			if(mkdir(*argv, S_IRWXU | S_IRWXG | S_IRWXO) == -1)
				perror("opendir");
			continue; //if null then continue 
		}
	
		for(int i = 0; i < 2; i++){
			int cnt = 0; 
			for(; dp = readdir(dir_fd);){
				if(i) printf("%s\n", dp->d_name); //first entry is self entry -> int i = 0 -> self entry )
				if(strcmp(dp->d_name, ".") && strcmp(dp->d_name, ".."))
					cnt++;
			}
			if(!cnt){rmdir(*argv); break;}
			rewinddir(dir_fd);
		}
		closedir(dir_fd);
	}
	return 0; 
}

code4-6

#include<stdio.h>
#include<unistd.h>
#include "error.h"

#define PATH_MAX 1024

int main(void){
	char path[PATH_MAX + 1];
	if(chdir("/tmp") < 0)
		perror("error chdir");
	else{
		if(getcwd(path, PATH_MAX) == NULL)
			perror("error getcwd");
		else
			printf("Current working directory changed to %s \n", path);
	}
}

code4-7

#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<string.h>

int main(int argc, char* argv[]){
	char *buf[256], tname[256];
	if((argc < 3 && argc > 4) || (argc == 4 && strcmp(argv[1], "-s"))){
		printf("Usage: %s <orig_file> <new_file>\n", argv[0]);
		return 1;
	}
	if(argc == 4)
		return symlink(argv[2], argv[3]);
	else
		return link(argv[1], argv[2]);
}

lab-6

#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/stat.h>
#include<dirent.h>
#include "error.h"
typedef struct dirent Dirent; 

int match(char *s1, char *s2){ // s1 = filename, s2 = suffix 
	int diff = strlen(s1) - strlen(s2);
	if(strlen(s1) > strlen(s2)) return (strcmp(&s1[diff], s2) == 0);
	else return (0);
}

int main(int argc, char* argv[]){
	Dirent *dp;
	DIR *dir_fd;
	
	dir_fd = opendir(argv[1]); //open the directory 

	while(dp = readdir(dir_fd)){ // if dp is null then break 

		if(dp->d_name == "."  || dp->d_name == "..") 
			continue; //if d_name is self or parent then continue 
		else{
			if(match(dp->d_name, argv[2])){ //compare the d_name and the suffix 
				printf("matched file's i node number: %ld\n", dp->d_ino); // if true print info of the file 
				printf("matched fils's filename: %s\n", dp->d_name);
			}
		}	
	}
	return 0; 
}

6주차

 

code6-1

#include<stdio.h>
#include<stdlib.h>
static void my_exit1(void), my_exit2(void);
void err_sys(const char* message);

int main(void){
	if(atexit(my_exit2) != 0)
		err_sys("can't register my_exit2");
	if(atexit(my_exit1) != 0)
		err_sys("can't register my_exit1");
	if(atexit(my_exit1) != 0)
		err_sys("can't register my_exit1");
	printf("main in done\n");
	return 0;
}

static void my_exit1(void){
	printf("first exit handler \n");
}
static void my_exit2(void){
	printf("second exit handler \n");
}
void err_sys(const char* message){
	fputs(message, stderr);
	fputc('\n', stderr);
	exit(1);
}

code6-2

#include<stdio.h>
#include<stdlib.h>
extern char **environ;

int main(){
	char **env = environ;

	while(*env){
		printf("%s\n", *env);
		env++;
	}
	exit(0);
}

code6-3

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(int argc, char *argv[]){
	char *var, *value;
	if(argc == 1 || argc > 3){
		fprintf(stderr, "usage: environ var [value]\n");
		exit(1);
	}
	var = argv[1];
	value = getenv(var);
	if(value)
		printf("Variable %s has value %s\n", var, value);
	else
		printf("Variable %s has no value\n", var);

}

lab-7

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>

int main(){

	char* var = "PATH"; 
	char* new_value; 
	char buff[1024]; //buffer

	printf("PATH is %s \n", getenv(var));
	getcwd(buff, 1024); // get current directory path to buff 
	new_value = buff;  //allocate current directory path to new_value 
	
	setenv(var, new_value, 1); //set new_value to PATH, if exists overwrite PATH 
	
	printf("Changed PATH is %s \n", getenv(var));

	return 0; 
}

7주차

code6-4

#include<stdio.h>
#include<stdlib.h>
#include<setjmp.h>

static void f1(int, int, int);
static void f2(void);

static jmp_buf jmpbuffer;

int main(void){
	int count;
	int val;
	int sum; 

	count = 2; val = 3; sum = 4;
	printf("initial values: count = %d, val = %d, sum = %d\n", count, val, sum);
	if(setjmp(jmpbuffer) != 0){
		printf("after longjmp: count = %d, val = %d, sum = %d\n", count, val, sum);
		exit(0);
	}
	count = 97; val = 98; sum = 99; 
	f1(count, val, sum);
}
static void f1(int i, int j, int k){
	printf("in f1(): count = %d, val = %d, sum = %d\n", i, j, k);
	f2();
}
static void f2(void){
	longjmp(jmpbuffer, 1);
}

code7-1

#include<stdio.h>
#include<unistd.h>

int main(void){
	int x;

	x = 0;
	fork();
	x = 1;
	printf("I am process %ld and my x is %d\n", (long)getpid(), x);
	return 0; 
}

code7-2

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main(void){
	pid_t childpid;

	childpid = fork();
	if(childpid == -1){
		printf("Failed to fork");
		return 1;
	}
	if(childpid == 0)
		printf("hello from child %ld\n", (long)getpid());
	else
		printf("hello from parent %ld\n", (long)getpid());
	return 0; 
}

code7-3

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>

void fork1(){
	int x = 1;
	pid_t pid = fork();
	if(pid == 0){
		printf("Child has x = %d\n", ++x);
	}else{
		printf("Parent has x = %d\n", --x);
	}
	printf("Bye from process %d with x = %d\n", getpid(), x);
}

int main(){
	fork1(); 
	return 0; 
}

code7-4

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>

void fork2(){
	printf("L0\n");
	fork();
	printf("L1\n");
	fork();
	printf("Bye\n");
}
int main(){
	fork2();
	return 0; 
}

code7-5

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>

void fork3(){
        printf("L0\n");
        fork();
        printf("L1\n");
        fork();
        printf("L2\n");
	fork();
	printf("Bye\n");
}
int main(){
        fork3();
        return 0;
}

code7-6

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>

void fork4(){
	printf("L0\n");
	if(fork() != 0){
		printf("L1\n");
		if(fork() != 0){
			printf("L2\n");
			fork();
		}
	}
	printf("Bye\n");
}
int main(){
	fork4();
	return 0; 
}

code7-7

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
void fork5(){
	printf("L0\n");
	if(fork() == 0){
		printf("L1\n");
		if(fork() == 0){
			printf("L2\n");
			fork();
		}
	}
	printf("Bye\n");
}
int main(){
	fork5();
	return 0; 
}

code7-8

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>

int main(){
	pid_t pid;
	char *message;
	int n;

	printf("fork program starting\n");
	pid = fork();
	switch(pid){
		case -1: 
			perror("fork failed");
			exit(1);
		case 0:
			message = "This is the child";
			n = 5;
			break;
		default:
			message = "This is the parent";
			n = 3;
			break;
	}
	for(;n>0;n--){
		puts(message);
		sleep(1);
	}
	exit(0);
}

code7-9

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>

int glob = 6;

int main(void){
	int var;
	pid_t pid;

	var = 88;
	printf("before fork\n");

	if((pid = fork()) < 0)
		perror("fork error");
	else if(pid == 0){
		glob++;
		var++;
		_exit(0);
	}

	printf("pid = %d, glob = %d, var = %d\n", getpid(), glob, var);
	exit(0);
}

code7-10

#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdlib.h>

int main(void){
	pid_t pid; 
	char* message; 
	int n;
	int exit_code;

	printf("fork program starting\n");
	pid = fork(); 
	switch(pid){
		case -1:
			perror("fork failed");
			exit(1);
		case 0:
			message = "This is the child";
			n = 5;
			exit_code = 37;
			break;
		default: 
			message = "This is the parent";
			n = 3;
			exit_code = 0;
			break;
	}
	for(;n>0;n--){
		puts(message);
		sleep(1);
	}
	if(pid != 0){
		int stat_val;
		pid_t child_pid;
		child_pid = wait(&stat_val);

		printf("Child has finished: PID = %d\n", child_pid);
		if(WIFEXITED(stat_val))
			printf("Child exited with code %d\n", WEXITSTATUS(stat_val));
		else
			printf("Child terminated abnormaly\n");
	}
	exit(exit_code);
}

code7-11

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>

int main(){
	int pid; 
	int status;
	pid = fork();
	if(pid < 0){
		perror("fork error: ");
		exit(0);
	}
	if(pid == 0){
		printf("I am Child\n");
		sleep(2);
		return 2; 
	}
	else{
		printf("Parent: wait (%d)\n", pid);
		waitpid(pid, &status, 0);
		if(WIFEXITED(status)){
			printf("normal exit\n");
			printf("return value %d\n", WEXITSTATUS(status));
		}
		else if(WIFSIGNALED(status)){
			printf("signal accpeted\n");
			printf("signal number %d\n", WTERMSIG(status));
		}
	}
	exit(0);
}

lab-8

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>

#define BUFSIZE 512

int main(){
        int pid;				 // pid 
	int status; 				 // termination status 
	int parent_pid = getpid();  	         // parent process's processID. 
	int string_length;                       // length of string in inputfileName
	char* inputfilename = "sample.txt";  	 // fetch string from this file. 
	char* outputfilename = "output.txt"; 	 // store string in this file. 
	
	int fd;					 // file descriptor of inputfile 
	int fd2; 				 // file descriptor of outputfile
	int nread; 
	int total; 
	char buffer[BUFSIZE]; 		          

	if((fd = open(inputfilename, O_RDWR)) < 0){ // open sample.txt 
		perror("file open error: fd1\n");
		exit(1); 
	}
	if((fd2 = open(outputfilename, O_RDWR)) < 0){ //open output.txt
		perror("file open error: fd2\n");
		exit(1);
	}

	while(nread = read(fd, buffer, BUFSIZE) > 0) // read content of sample.txt 
		total += nread;
	
	// print the information 
	printf("buffer content: %s\n", buffer);
	printf("string length: %ld\n", strlen(buffer));  
	
	string_length = strlen(buffer); // if string is "system" then string_length = 7 because of \0 

	// make child process per loop, child process's count limit = string size - 1
	// because of \0 added end of the string 
	while(--string_length){ // will loop length of string - 1 
		pid = fork(); 	// create child process 
		if(pid < 0){
			perror("fork error\n");
			exit(1);
		}
		if(pid == 0) 	// if child process then endwhile 
			break;
		else{	 	// if parent process then wait until child exit 
			//sleep(1); 
			waitpid(pid, &status, 0); // wait child process 
		}
	} 

	// only child process execute this contidion.  
        if(pid == 0){ // if child process do 
		
		int child_pid = getpid(); // get self pid; 
		int order = child_pid - parent_pid; // order variable is the order of the child process created by parent process.   
                char i = 0; 		   
		while(order--){
			write(fd2, (void*)(buffer+ i), 1); // write 1byte from buffer to output.txt 
			i++; 			          // index 
		}
	      	write(fd2, "\n", 1);		          // add newline to output.txt
        	exit(0); // child process will exit here. means return  
	}
	else{   
                printf("Parent: wait (%d)\n", pid);

                //waitpid(pid, &status, 0);
                if(WIFEXITED(status)){
                        printf("normal exit\n");
                        printf("return value %d\n", WEXITSTATUS(status));
                }
                else if(WIFSIGNALED(status)){
                        printf("signal accpeted\n");
                        printf("signal number %d\n", WTERMSIG(status));
                }
        }
	
	printf("closing file.\n");
	printf("operation finished. \n");	

	close(fd); 	// close inputfile descriptor: sample.txt
	close(fd2);     // close outputfile descriptor: output.txt 
      
      	exit(0);  
}

8주차

code7-12

#include<stdio.h>
#include<unistd.h>
main(int argc, char* argv[]){
	execl("/bin/ls", "ls", argv[1], (char*)0);
}

code7-13

#include<stdio.h>
#include<unistd.h>
main(){
	char *av[3];

	av[0] = "ls";
	av[1] = "-l";
	av[2] = (char*) 0;

	execv("/bin/ls", av);
}

code7-14

#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>

void usage(void);
char *command_name;
main(int argc, char* argv[]){
	char *rindex(const char* s, int c);
	
	if((command_name = rindex(argv[0], '/')) != NULL) command_name++;
	else command_name = argv[0];
	if(argc < 2) usage(); 
	if(execv(argv[1], &argv[1]) == -1){
		perror("execv");
		exit(1);
	}
}
void usage(void){
	fprintf(stderr, "Usage: %s command [option]\n", command_name);
	exit(1);
}

code7-15

#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
static void charatatime(char*);

int main(void){
	pid_t pid;

	if((pid = fork()) < 0) perror("fork error");
	else if(pid == 0) charatatime("output from child\n");
	else charatatime("output from parent\n");
	exit(0);
}
static void charatatime(char* str){
	char* ptr;
	int c;
	setbuf(stdout, NULL);
	for(ptr = str; c = *ptr++; )
		putc(c, stdout);
}

code7-16

#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<errno.h>
#include<unistd.h>
#include<stdlib.h>
int system(const char* cmdstring){
	pid_t pid;
	int status; 

	if(cmdstring == NULL)
		return (1);
	if((pid = fork()) < 0)
		status = -1; 
	else if(pid == 0){
		execl("/bin/sh", "sh", "-c", cmdstring, (char*) 0);
		_exit(127);
	}else{
		while(waitpid(pid, &status, 0) < 0)
		if(errno != EINTR){
			status = -1;
			break;
		}
	}
	return (status); 
}
int main(){
	if(system("ls -l") < 0){ // give ls -l command for example 
		perror("system error");
		exit(1);
	}
	return 0; 
}

code7-17

#include<stdio.h>
#include<sys/times.h>
#include<time.h>
#include<unistd.h>
#include<stdlib.h>
static void pr_times(clock_t, struct tms*, struct tms*);
static void do_cmd(char*);

int main(int argc, char* argv[]){
	int i;
	for(i = 1; i<argc; i++)
		do_cmd(argv[i]);
	exit(0);
}
static void do_cmd(char* cmd){
	struct tms tmsstart, tmsend; 
	clock_t start, end;
	int status; 

	fprintf(stderr, "\ncommand: %s\n", cmd);
	if((start = times(&tmsstart)) == -1)
		perror("times error");
	if((status = system(cmd)) < 0)
		perror("system() error");
	if((end = times(&tmsend)) == -1)
		perror("times error");
	pr_times(end - start, &tmsstart, &tmsend);
}
static void pr_times(clock_t real, struct tms *tmsstart, struct tms* tmsend){
	static long clktck = 0; 
	if(clktck == 0){
		if((clktck = sysconf(_SC_CLK_TCK)) < 0)
			perror("sysconf error");
	}
	fprintf(stderr, "real: %7.2f\n", real/(double)clktck);
	fprintf(stderr, "user: %7.2f\n", (tmsend->tms_utime - tmsstart->tms_utime) / (double) clktck);
	fprintf(stderr, "sys: %7.2f\n", (tmsend->tms_stime - tmsstart->tms_stime)/ (double) clktck);
	fprintf(stderr, "child user: %7.2f\n", (tmsend->tms_cutime - tmsstart->tms_cutime)/ (double) clktck);
	fprintf(stderr, "child sys: %7.2f\n", (tmsend->tms_cstime - tmsstart->tms_cstime)/ (double) clktck);
}

lab-9

#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
main(){
		
	int pid; 
	int status;
	int parent_pid = getpid(); 
        int self_pid; // own pid 	
	int order; 
	char* order_char; 
	char message[20] = "This is Chiid";

   	int count = 0; 

	pid = fork();      // create child -> child1
	if(pid < 0){
		perror("fork error");
		exit(1);
	}
	else if(pid > 0){   // if process is  parent create another child -> child2 
		pid = fork();
		if(pid < 0){
			perror("fork error");
			exit(1);
		}
	}

	if(pid == 0){ // if process is child then 

		parent_pid = getppid(); // get parent process pid;
		self_pid = getpid();    // get self pid; 
		order = self_pid - parent_pid; 
		
		if(order == 1){
			strcat(message, "1");
		}
		else if(order == 2){
			strcat(message, "2");
		}
	
		if(execl("/usr/bin/echo","echo", message, (char*)0) == -1){
			perror("execl");
			exit(1); 
		}
	}else{       // if process if parent then 
	        printf("Parent: Waiting for children\n");
		int stat_val; 
		pid_t child_pid; 
		while(count != 2){               // looping until all child is exited 
			child_pid = wait(&stat_val);
			if(child_pid>parent_pid)
				count++; 
		}
	}
	if(count == 2){  // if all child has exited well do print 
		printf("Parent: All Children terminated\n");
	}
}

lab-10

#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
main(){

        int pid;
        int status;
        int parent_pid = getpid();
        int self_pid; // own pid        
        int order;
        char* order_char;
        char message[20] = "This is Chiid";

        int count = 0;

        pid = fork();      // create child -> child1
        if(pid < 0){
                perror("fork error");
                exit(1);
        }
        else if(pid > 0){   // if process is  parent create another child -> child2 
                pid = fork();
                if(pid < 0){
                        perror("fork error");
                        exit(1);
                }
        }

        if(pid == 0){ // if process is child then 

                parent_pid = getppid(); // get parent process pid;
                self_pid = getpid();    // get self pid; 
                order = self_pid - parent_pid;

                if(order == 1){
                        strcat(message, "1");
                }
                else if(order == 2){
                        strcat(message, "2");
                }

                if(execl("/usr/bin/echo","echo", message, (char*)0) == -1){
                        perror("execl");
                        exit(1);
                }
        }else{       // if process if parent then 
                printf("Parent: Waiting for children\n");
                int status;
                pid_t child_pid;
                while(count != 2){               // looping until all child is exited 
                        child_pid = wait(&status);

			if(child_pid - parent_pid == 2){
				printf("Parent: Second Child: \n");
			}else if(child_pid - parent_pid == 1){
				printf("Parent: First Child: \n");
			}

                        if(WIFEXITED(status)){
				printf("status: %d\n", WEXITSTATUS(status));
				count++; 
			}
			else if(WIFSIGNALED(status)){
				printf("signaled\n");
				printf("signal number %d\n", WTERMSIG(status));
			}
                }
        }
        if(count == 2){  // if all child has exited well do print 
                printf("Parent: All Children terminated\n");
        }
}

9주차

code8-1

#include<stdio.h>
#include<signal.h>
#include<unistd.h>
void ouch(int);
main(){
	signal(SIGINT, ouch);
	while(1){
		printf("Hello World!\n");
		sleep(1);
	}
}
void ouch(int sig){
	printf("OUCH -l got signal %d\n", sig);
	(void) signal(SIGINT, SIG_DFL);
}

code8-2

#include<stdio.h>
#include<signal.h>
#include<stdlib.h>
#define OUTPUT "count-prime.out"
#define MAXNUM 100000

int count;
FILE *fptr;
void sigcatch(); 

main(){
	int number, divisor; 
	void sigcatch();

	fptr = fopen(OUTPUT, "w");
	signal(SIGINT, sigcatch);
	for(number = 1; number <= MAXNUM; number++){
		for(divisor = 2; divisor < number; divisor++)
			if((number % divisor) == 0) 
				break;
		if(divisor == number){
			fprintf(fptr, "%d \n", number); 
			count++;
		}
	}
	fclose(fptr);
}
void sigcatch(){
	printf("%d primes computed \n", count);
	fclose(fptr);
	exit(1);
}

lab-11

#include<stdio.h>
#include<stdlib.h>
#include<signal.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<unistd.h>
void int_handler(int sig){ // handler function 
	printf("Process %d received signal %d\n", getpid(), sig);
	exit(0);
}
main(){
	int pid;
	pid = fork(); // create child
	if(pid < 0){
		perror("fork error");
		exit(1);
	}  

	if(pid == 0){ // if child process do 
		signal(SIGINT, int_handler); // register signal handler 
		while(1){} // infinite loop  
	}
	if(pid != 0){ // if parent process do 
		int status; 
		if(kill(pid, SIGINT) < 0){ // kill child process
		        perror("kill error");
			exit(1); 
		}	
		wait(&status); // waiting child process 

		if(WIFEXITED(status)){
			printf("child exited with code %d\n", WEXITSTATUS(status));
		}
		else{   // child process is signaled -> else will execute. 
			printf("Child terminated abnormaly\n"); 
		}
	}
}

lab-12

parent.c

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<signal.h>
main(){
	int pid; 
	pid = fork(); //create child process
	if(pid < 0){
		perror("fork error");
		exit(1);
	}

	if(pid == 0){ // if child process then do 
		//execl("/home/razelo/assign/9week/lab#12/child", "./child", (char*)0); 
		execlp("./child", "./child", (char*) 0); // use env PATH 
	}
	if(pid != 0){ // if parent process then do 
		int status;
	        int child_pid; 	
		printf("parent: child initiated\n");
		
		sleep(3); // wait 3 sec then kill child process 
		
		kill(pid, SIGTERM); // signal to child process 
		child_pid = wait(&status);
		
		if(child_pid == pid){ // if child process terminated neither normaly, abnormaly then do  
			printf("parent: child terminated\n"); 
		}
	}
}

child.c

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
main(){
	//printf("child is executed\n");
	sleep(30); // sleep 30 sec  
}

 

 

반응형