Вопрос

This is the question that I saw in the exam:

Explain the circumstances under which which the line of code marked printf("LINE J") in Figure 3.33 will be reached.

enter image description here

The only answer that came to my mind was this: when fork returns 0 we are at child process and so j would be printed but I feel it is not that simple could you please say your idea if any other possibilities exists?

Это было полезно?

Решение

If the fork works but the execlp doesn't, that's when that line will be printed, and only in the child process.

If for some reason the fork fails (for example, you've exceeded resource quotas), no child is created and the parent will simply go through the if (pid < 0) code.

If both the fork and the execlp work, execlp replaces the contents of the child process with the /bin/ls executable so no code in the original program exists after that point.

There are several ways the execlp could fail, among them (not an exhaustive list):

  • the permissions forbid it.
  • some prankster has moved or deleted the /bin/ls executable.
  • it exists elsewhere else in the file system (a).
  • it's been corrupted.

(a) Although hopefully it would be in your path somewhere in which case you may be better off using "ls" as the first argument to execlp so that it can find it there. Otherwise, there's little point using execlp and you may as well just use execl since you're not using the path-search feature when you begin the executable name with /.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top