Operating Systems: System Calls, Processes, and Forking

Classified in Computers

Written on in with a size of 2.83 KB

Operating Systems: System Calls and File Descriptors

OS vs. User ModeRead vs. Write OperationsSpecial File Descriptors

System Calls and Kernel Mode

Public functions provided by the OS.

open(*pathname, Flags): Returns a file descriptor; returns -1 on error.

int main(int argc, char *argv[]) {
  int fd = open(argv[1], O_WRONLY | O_CREAT | O_EXCL, 0644);
  if (fd == -1) {
    printf("There was a problem creating \"%s\"!\n", argv[1]);
    return 1;
  }
  close(fd);
  return 0;
}

Handling Data Streams

read may not return all requested bytes; it returns the actual count read. It only returns 0 at the end of the file.

void copyContents(int sourceFD, int destinationFD) {
  char buffer[kCopyIncrement];
  while (true) {
    ssize_t bytesRead = read(sourceFD, buffer, sizeof(buffer));
    if (bytesRead == 0) break;
    size_t bytesWritten = 0;
    while (bytesWritten < sizeof(buffer)) {
      ssize_t count = write(destinationFD, buffer + bytesWritten, sizeof(buffer) - bytesWritten);
      bytesWritten += count;
    }
  }
}

Note: Always loop writes as the OS may not write all data at once.

Standard Descriptors

  • 0: STDIN_FILENO (Standard Input)
  • 1: STDOUT_FILENO (Standard Output)
  • 2: STDERR_FILENO (Error Output)

Multiprocessing and Process Management

ConceptsPID and ForkingShell Logic

Programs vs. Processes

  • Program: Code written to execute tasks.
  • Process: An instance of a program running with its own execution state.

Single-core: Switches between tasks rapidly.
Multi-core: True parallel execution.

The Fork Mechanism

The OS assigns each process a unique PID (getpid()). fork() creates a clone of the process.

  • Fork returns: Child's PID in the parent, 0 in the child.
  • Copied info: File descriptor table, memory regions (stack, heap).

Shell Execution

A shell prompts for commands, waits for completion, and repeats. It maintains linear execution flow between parent and child.

Process Clones

Virtual addresses remain identical, but physical addresses differ. Systems use Copy-on-Write to share memory until a modification occurs.

Related entries: