Skip to content

Instantly share code, notes, and snippets.

@sriramster
Created February 16, 2021 05:46
Show Gist options
  • Save sriramster/98c0efbeb19b10431ca1474475604a2d to your computer and use it in GitHub Desktop.
Save sriramster/98c0efbeb19b10431ca1474475604a2d to your computer and use it in GitHub Desktop.
Sys call experiments
#include <dirent.h>
#include <error.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <signal.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
void sig_handler(int sig)
{
switch(sig) {
case SIGINT:
case SIGTSTP:
case SIGTRAP:
case SIGABRT:
case SIGFPE:
case SIGUSR1:
case SIGUSR2:
case SIGSEGV:
case SIGSTOP:
case SIGCHLD:
default:
printf("\n Ignoring signals except kill");
}
}
void cur_time(void)
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ("\nCurrent local time and date: %s", asctime (timeinfo));
}
void child_process(void)
{
DIR *d;
struct dirent *de;
struct stat buf;
int exists;
printf("\n Opening the current directory");
d = opendir(".");
if (d == NULL) {
fprintf(stderr, "Error opening current directory\n");
exit(-1);
}
for (de = readdir(d); de != NULL; de = readdir(d)) {
exists = stat(de->d_name, &buf);
if (exists < 0) {
fprintf(stderr, "%s not found\n", de->d_name);
} else {
printf("%s %ld\n", de->d_name, buf.st_size);
}
}
}
int main(int argc, char **argv)
{
pid_t cpid;
printf("\n PID of parent is : %ld", (long)getpid());
signal(SIGINT, sig_handler);
signal(SIGTSTP, sig_handler);
signal(SIGTRAP, sig_handler);
signal(SIGABRT, sig_handler);
signal(SIGFPE, sig_handler);
signal(SIGUSR1, sig_handler);
signal(SIGUSR2, sig_handler);
signal(SIGSEGV, sig_handler);
signal(SIGSTOP, sig_handler);
signal(SIGCHLD, sig_handler);
child:
if ((cpid = fork()) != -1)
{
while(1) {
printf("\n PID of child is : %ld", (long)getpid());
cur_time();
child_process();
sleep(10);
}
}
else
{
wait(NULL);
goto child;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment