feat: 2106 misc

This commit is contained in:
Yadunand Prem 2023-11-04 19:19:48 +08:00
parent 4bbd2c2be6
commit 9183d82953
No known key found for this signature in database
4 changed files with 103 additions and 0 deletions

View File

@ -0,0 +1,32 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/shm.h>
int main() {
int shmid, *shm;
shmid = shmget(IPC_PRIVATE, 4, IPC_CREAT | 0600);
if (shmid == -1) {
printf("Cannot create shared memory!\n");
exit(1);
} else {
printf("Shared memory ID = %d\n", shmid);
}
shm = (int*) shmat(shmid, NULL, 0);
if (shm == (int*) -1) {
printf("Cannot attach shared memory!\n");
exit(1);
}
shm[0] = 0;
while(shm[0] == 0) {
sleep(3);
}
for(int i = 0; i < 3; i++) {
printf("Read %d from shared memory. \n", shm[i+1]);
}
shmdt((char*) shm);
shmctl(shmid, IPC_RMID, 0);
}

View File

@ -0,0 +1,26 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/shm.h>
int main() {
int shmid, input, *shm;
printf("Shared memory id: ");
scanf("%d", &shmid);
shm = (int*) shmat(shmid, NULL, 0);
if (shm == (int*) -1) {
printf("Error: Cannot attach!\n");
exit(1);
}
for(int i = 0; i < 3; i++) {
scanf("%d", &input);
shm[i+1] = input;
}
shm[0] = 1;
shmdt((char*) shm);
return 0;
}

View File

@ -0,0 +1,24 @@
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#define READ_END 0
#define WRITE_END 1
int main() {
int pipeFd[2], pid, len;
char buf[100], *str = "Hello There!";
pipe(pipeFd);
if ((pid = fork()) > 0) {
close(pipeFd[READ_END]);
write(pipeFd[WRITE_END], str, strlen(str) +1);
close(pipeFd[WRITE_END]);
} else {
close(pipeFd[WRITE_END]);
len = read(pipeFd[READ_END], buf, sizeof(buf));
printf("Proc %d read: %s\n", pid, buf);
close(pipeFd[READ_END]);
}
}

View File

@ -0,0 +1,21 @@
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
void myOwnHandler(int signo) {
if (signo == SIGSEGV) {
printf("Memory Access blows up!\n");
exit(1);
}
}
int main() {
int *ip = NULL;
if (signal(SIGSEGV, myOwnHandler) == SIG_ERR)
printf("Failed to register handler\n");
*ip = 123;
return 0;
}