본문 바로가기
시스템/시스템보안

(2) Linux basic

by 주황딱지 2024. 7. 8.

기본 명령어

 

List

$ ls [directory]
$ ls –al [directory]

 

Change directory

$ cd [directory]

 

Read file

$ cat [file]

 

Create/Write file

$ vim [file]

• Enter ‘i’ for inserting mode(editing mode)

• Enter ‘esc’ for quitting insert mode.

• Enter ‘:wq+ENTER’ to write and save the file

 

Make directory

$ mkdir [directory]

 

Move fiile

$ mv [src path] [dest path]

 

Remove file/ directory

$ rm [file]
$ rm –rf [directory]

 

Copy file

$ cp [src path] [dest path]

 

Print working directory

$ pwd

 

Compile and run the C file

$ gcc –o [target] [source file]
$ gcc –o test test.c

 

 

Play with system calls and std lib

 

여기서 시스템 콜과 기본 라이브러리 기능들의 설명을 볼 수 있다: https://www.kernel.org/doc/man-pages/

 

Write a file

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

int main(int argc, char* argv[]) {
int fd;
char buf[] = "hello, world\n";

printf("Open a new file\n");
if ((fd = open("./test_file", O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) == -1) {
perror("open()");
return 1;
}

printf("Write the file\n");
write(fd, buf, strlen(buf));

printf("Close the file\n");
close(fd);

return 0;
}

 

Read a file

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

int main(int argc, char* argv[]) {
int fd;
char buf[1024];

printf("Open a new file\n");
if ((fd = open("./test_file", O_RDONLY)) == -1) {
perror("open()");
return 1;
}

printf("Read the file\n");
memset(buf, 0, sizeof(buf));
read(fd, buf, sizeof(buf));
puts(buf);

printf("Close the file\n");
close(fd);

return 0;
}

 

Standard Input & Output

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

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

setvbuf(stdin, NULL, _IONBF, 0);
setvbuf(stdout, NULL, _IONBF, 0);

memset(buf, 0, sizeof(buf));

printf("Enter: ");
read(0, buf, sizeof(buf));

printf("You have entered...\n");
write(1, buf, sizeof(buf));

return
}

 

Get PID & PPID

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

int main() {

pid_t pid;
pid_t ppid;

pid = getpid();
ppid = getppid();

printf("pid: %d\n", pid);
printf("parent pid: %d\n", ppid);

return 0;
}

Spawn child process

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

int main(int argc, char* argv[]) {
pid_t pid;
int status;

pid = fork();

if (pid == 0) { // child proc
 printf("I'm child proc(%d).\n", getpid());

 exit(10);
} 

else if (pid > 0) { // parent proc
 printf("child's pid: %d\n", pid);
 wait(&status);

 if (WIFEXITED(status)) {
printf("normal exit with status %d\n", WEXITSTATUS(status));
}
}

else {// error
perror("fork");

return 1;
}

return 0;
}
반응형

'시스템 > 시스템보안' 카테고리의 다른 글

(3) Permission  (0) 2024.07.11
(1-5) OS  (0) 2024.07.08
(1-4) OS  (0) 2024.07.07
(1-3) OS  (0) 2024.07.06
(1-2) OS  (1) 2024.07.05