- Linux против Solaris
- Различия между Linux и Solaris
- Linux
- Solaris
- Сравнение лицом к лицу между Linux и Solaris (инфографика)
- Ключевые различия между Linux и Solaris
- Сравнительная таблица Linux и Solaris
- Вывод — Linux против Solaris
- Рекомендуемые статьи
- Comparison of Solaris OS and Linux for Application Developers
- Contents
- Introduction
- System Calls and Libraries
- Table 1: Some Libraries in Linux and Solaris OS
- Sockets and Networking
- Networking Example
- Process/Processor Management
- Threads
- Similarities
- Differences
- Synchronization
- Memory Management
- Timers
- Signal Handling
- Conclusions
Linux против Solaris
Различия между Linux и Solaris
Linux является операционной системой с открытым исходным кодом. Linux это не программа. Это интерфейс между программным и аппаратным обеспечением. Linux является одним из лучших программ, обеспечивающих высокую стабильность и зависимость. Linux бесплатен и легко доступен, так как не зависит от платформы. Solaris — это операционная система, основанная на ОС UNIX. Солярис был написан на языке Си и Си ++. Solaris поддерживает платформы SPARC и Power PC. Solaris был создан с концепцией открытого исходного кода и включал в себя исходный код, включая библиотеки, команды и ядро.
Linux
- Linux был разработан Линусом Торвальдсом и выпущен в 1991 году. В Linux новые изменения, такие как обновление компонентов, модификации, настройка компонентов, действительно просты, не создавая проблем с существующими компонентами.
- Терминология Linux состоит из загрузчика, init-программы, ядра, системной библиотеки, системной утилиты. Linux имеет широкий спектр дистрибутивов: 1. Ubuntu Linux 2. Linux Mint 3. Arch Linux 4. Deepin 5. Fedora 6. Debian 7. Открывает Use.
- Каждый дистрибутив отличается и имеет разные интерфейсы друг к другу. Можно выбрать распределение в зависимости от их требований. Архитектура Linux в основном разделена на две части или слои, то есть уровень ядра и уровень пользователя. Уровень ядра состоит из интерфейса, кода ядра, пакета поддержки платы.
Solaris
- Изначально Solaris был создан Sun Microsystems и выпущен в 1992 году. Изначально Solaris лицензировал программное обеспечение и должен получить лицензии для установки на компьютеры. После того, как Oracle приобрела Sun Microsystems в 2010 году, она была переименована в Oracle Solaris. Oracle прекращает работу с открытым исходным кодом Solaris.
- Oracle предоставляет 90-дневную бесплатную пробную версию программного обеспечения для использования. Чтобы продолжить работу с программным обеспечением после бесплатного пробного дня, нам нужно будет приобрести лицензию у Oracle, чтобы использовать Solaris в качестве платформы разработки.
- За прошедшие годы Oracle выпустила Solaris с новыми функциями и улучшениями, такими как средства управления службами, зоны ядра и другие службы. Считается, что Oracle Solaris легко обновлять облачные установки и используется для устаревших приложений в облачной среде, обеспечивая высочайшую безопасность и производительность.
Сравнение лицом к лицу между Linux и Solaris (инфографика)
Ниже приведено 8 лучших сравнений между Linux и Solaris.
Ключевые различия между Linux и Solaris
Несмотря на то, что оба Linux и Solaris имеют много общего, они также имеют много отличий; мы рассмотрим эти различия между Linux и Solaris более подробно:
- Linux имеет меньшую стабильность. Solaris обладает более устойчивой стабильностью по сравнению с Linux.
- У Linux есть базовое планирование. Solaris обладает широким спектром планирования и возможностью использования и настройки при необходимости.
- Linux имеет стандартную возможность ввода-вывода. Солярис имеет широкую многостраничную поддержку COMSTAR.
- В Linux есть старый сервисный механизм, так как SVR4, который основан на тексте, не допускает никакой зависимости, и конфигурация сервисов не может быть отменена. В Solaris появился новый сервисный механизм с великолепными функциями, такими как SMF, который основан на конфигурации x ml, позволяет при необходимости восстанавливать зависимости и конфигурации.
- Linux не зависит от платформы. Solaris недоступен для некоторых платформ, но доступен для разных архитектур.
- Linux обеспечивает хорошую безопасность и производительность. Solaris обеспечивает строгую функцию безопасности, которая дает большую безопасность для производительности.
- Linux обладает хорошими способностями администратора. Solaris обладает отличной способностью администратора, которая позволяет легко устанавливать и администрировать систему.
- Поддержка Linux в основном предоставляется Red Hat. Поддержка Solaris, предоставляемая Oracle (после приобретения Sun Microsystem).
- Сертификационный онлайн-тренинг по XML и Java
- Программа Node.JS
- Сертификация C ++ и DirectX
- Учебные курсы Гудини
Сравнительная таблица Linux и Solaris
Ниже приведена сравнительная таблица между Linux и Solaris.
ОСНОВА ДЛЯ СРАВНЕНИЕ | Linux | Solaris |
Предназначены | Linux предназначен для встраивания, планшетов и телефонов. | Солярис не предназначен для того же. |
пропускная способность | У Linux хорошая пропускная способность. | Солярис обладает отличной пропускной способностью. |
Запрограммированный | Linux был написан на языке Си. | Солярис был написан на языке Си и Си ++. |
Совместимость | У Linux хорошая двоичная совместимость. | У Solaris отличная двоичная совместимость. |
Платформа | Linux поддерживает IBM Power и Z серии. | Solaris поддерживает SPARC и Power PC. |
Обновить | Для Linux инструменты обновления используются для обновлений. | Solaris обновляется с помощью обновлений программного обеспечения. |
Установка | Кикстарт-установка. | Автоматический установщик используется для установки. |
управление | У Linux нет такой возможности. | У Solaris есть средство управления системой (SMF). |
Вывод — Linux против Solaris
Linux и Solaris являются операционной системой. Это UNIX-подобные системы, имеющие сходство в виртуальной памяти, процессах, ядрах, подкачке страниц, системных вызовах, буфере, кеше, поддержке многопроцессорных систем, планировании и поддержке ЦП, средствах управления ресурсами, отображаемых файлах и т. Д. Linux и Solaris имеют различный набор командной строки Команда использовать. Если вы знакомы с одним, было бы легко использовать другой.
Linux в основном используется, потому что это с открытым исходным кодом. Linux бесплатен и доступен. Linux можно легко скачать и установить на машинах столько, сколько потребуется. Solaris имеет лицензионное программное обеспечение; Лицензия должна быть получена от Oracle, чтобы установить ее на компьютерах. Количество полученных лицензий равно числу машин, которые необходимо установить.
Oracle Solaris не имеет такой популярности, как Linux. Solaris в основном используется из-за факторов безопасности и производительности. Solaris является безопасным, простым, облачным и готовым к работе в облаке, поскольку обеспечивает отличную совместимость с инструментами управления для простой и эффективной работы инфраструктуры в облаке.
Linux и Solaris учатся друг у друга и внедряют инновации, а также внедряют новые функции по мере необходимости. Исходя из вышеизложенного, вы будете иметь представление о различиях и возможностях Linux и Solaris.
В наши дни организации выбирают операционную систему с умом, для них главное — безопасность. В современном мире существует так много типов вирусов, что вредоносное ПО делает вашу систему медленной и небезопасной. Безопасность системы находится на вершине списка, что также обеспечит хорошую производительность систем.
Рекомендуемые статьи
Это было руководство по различиям между Linux и Solaris, их значению, сравнениям между собой, ключевым различиям, сравнительной таблице и выводам. Эта статья состоит из всех полезных отличий между Linux и Solaris. Вы также можете посмотреть следующие статьи, чтобы узнать больше —
- Perl vs Ruby — различия
- Различия между Java и Node JS
- Linux против Windows — узнайте 9 самых удивительных отличий
- Программирование против сценариев — какой из них полезен (Инфографика)
- C ++ против Java — узнай 8 самых важных сравнений
- Perl против Python — 8 удивительных сравнений, которые вы должны знать
- Linux против Windows Server: какой из них полезен
- Linux против BSD: каковы особенности
- C ++ против Go: какой из них лучше
- Linux против Android: каковы особенности
- Руководство по основным отличиям iPhone от Android
Источник
Comparison of Solaris OS and Linux for Application Developers
By Max Bruning, June 2006
Contents
Many developers are writing applications to run under the Linux operating system. With the many new features of the Solaris 10 OS, and with the new emphasis Sun has placed on supporting the Solaris OS on AMD and Intel processor-based machines, developers are becoming interested in being able to develop their applications on the Solaris platform. This article examines similarities and differences in the development environments of both operating systems. Someone responsible for porting applications from Linux to the Solaris OS, or programmers with prior Linux experience that want to learn development on the Solaris OS, should benefit from this article.
In this article, the term «Solaris» refers to the Solaris 10 OS (and OpenSolaris), and «Linux» refers to Linux 2.6. Many of the details covered will also apply to earlier versions of Solaris and Linux. The Linux distribution is meant to be generic, though examples have been tested on SuSe 9.1. Also, the article concentrates on applications written using the C programming language, though C++ should behave the same. Since Java technology-based applications should not be making function calls specific to Linux or the Solaris OS, they should be portable as is.
Introduction
This article discusses similarities and differences that will be visible to application programmers and analysts on the Solaris OS and Linux. It is not meant as an exhaustive description of differences, nor is it meant to show that one OS is superior to the other. Rather, the article tries to help developers experienced in one of the OSes to work with the other OS as quickly as possible.
A simple application that is POSIX-compliant and doesn’t make any system calls or library functions specific to the Solaris OS or Linux should be portable between the OSes without changes. You should be able to write your app, compile for the Solaris OS or Linux, and simply recompile for the other OS, and it should work. Most of the system calls and library routines on both OSes will fall into this category.
Many system calls in Linux exist as library functions in the Solaris OS, and vice versa. For instance, sched_setscheduler() is a system call in Linux and a library function that calls the priocntl(2) system call in the Solaris OS. The priocntl(2) system call does not exist in Linux, but Linux does not support multiple schedulers beyond time share and real time. The next section of this article groups system calls into functional sections and compares what is available in each OS.
Most of the applications and toolkits from the Linux world will compile and run without changes. These include gcc, emacs, MySQL, perl, and many others. Precompiled binaries for many packages are available at http://www.sunfreeware.com.
Various administrative differences exist between the Solaris OS and Linux, and within Linux, between different distributions. The Solaris 10 OS has introduced the «Service Management Framework» (SMF), which is a big change from previous versions of Solaris. Coverage of system administration differences will not be handled in this paper, except where it affects developers.
System Calls and Libraries
Most of the system calls and libraries that exist in Linux also exist in the Solaris OS. This section will cover system calls and library routines that are different between the two systems. The system calls and library routines are categorized as follows:
The Solaris OS keeps a list of system calls in /usr/include/sys/syscall.h . Linux maintains the same information in /usr/include/asm/unistd.h . (Note that both Linux and the Solaris OS have unistd.h and syscall.h files, and that in some cases, the files agree in content.)
Documentation for system calls is available in the Solaris OS and on Linux at /usr/share/man/man2 . (The Solaris OS has a symbolic link from /usr/man to the same place.) Library routines are documented in various manual sections. See man intro.3 for an overview of the library sections on Linux and on the Solaris OS. Note that the Solaris OS breaks down the library routines more finely than Linux. For instance, aio_read() is documented at aio_read(3RT) on the Solaris OS, while on Linux, it is documented at aio_read(3) . The result of this is that when compiling a program using aio_read() on the Solaris OS, one must include the real-time library via -lrt with the compilation/link command, which is not necessary on Linux.
Both Linux and the Solaris OS come with over 200 different libraries, with more than 50,000 functions defined within the libraries.
The following table lists some libraries on Linux and the Solaris OS. Note that this is not meant to be a complete listing. Also note that some of these libraries must be downloaded and installed separately from normal installation of the system.
Table 1: Some Libraries in Linux and Solaris OS
Solaris OS inet_* routines) | ||
---|---|---|
libnsl | libnsl/libc | Network services library (linux — nis/nis+ routines) |
librpc | librpc | RPC functions |
libslp | libslp | Service Location Protocol |
libsasl | libsasl | Simple Authentication and Security Layer |
libaio | libaio | Asynchronous I/O library |
libdoor | Door support ( door_create() , door_return() , etc.) | |
librt | librt | POSIX Real Time library |
libcfgadm | Configuration administration library | |
libcontract | Contract management library (see man contract.4 on Solaris OS) | |
libcpc | CPU performance counter library (on Linux, may need to install kernel module?) | |
libdat | Direct Access Transport Library (see http://www.datcollaborative.org) | |
libelf | libelf | ELF support library |
libm | libm | Math library |
The next sections take a closer look at some of the system calls and libraries. We’ll concentrate on what’s different between the systems.
Sockets and Networking
Most of the socket and networking code should simply need to be recompiled for the OS you are using, and the resulting executable should work. This section compares network-related system calls and library routines that are typically used on the Solaris OS and Linux.
The socket() routine, in addition to the AF_UNIX , AF_INET , and AF_INET6 domain arguments, has additional values on the Solaris OS and Linux. On the Solaris OS, the AF_NCA domain is used to specify the Network Cache and Accelerator (see nca(1) ) for use with a socket. Most of the address families (domains) exist on both Linux and the Solaris OS. Note: See /usr/include/sys/socket.h on the Solaris OS and /usr/include/linux/socket.h for the possible address families. But you may need to download or write code to support some of the domains.
Linux has several additional domains documented on the socket(2) man page. The additional documented domains on Linux are:
- AF_IPX — Novell IPX protocols (may be for SuSe only?).
- AF_NETLINK — Kernel/user interface device, allows users to access kernel modules. Note: Other ways exist to do this on the Solaris OS (and on Linux for that matter).
- AF_X25 — X25 protocol. On the Solaris OS, this domain is included with Solstice X.25 product.
- AF_AX25 — Amateur radio AX.25 protocol.
- AF_ATMPVC — Permanent Virtual Circuits over ATM.
- AF_APPLETALK — See man ddp on Linux. Also exists on the Solaris OS but not documented.
- AF_PACKET — See man packet.7 on Linux. Raw packet interface. On the Solaris OS, open the NIC device and use getmsg(2)/putmsg(2) to receive/send raw packets using DLPI. (See Data Link Provider Interface (DLPI), Version 2 for details on DLPI).
bind()
The Linux man page ( man bind.2 ), includes some information about different address families besides AF_INET and AF_UNIX . The Solaris man page is man bind.3socket .
listen()
On both Linux and the Solaris OS, the backlog argument (the second argument to listen() ) refers to the queue length for established connections that are waiting to be accepted. The Linux man page says this, while the Solaris man page just refers to the «queue of pending connections».
accept()
Linux supports three connection-based socket types: SOCK_STREAM , SOCK_SEQPACKET , and SOCK_RDM , whereas the Solaris OS only documents SOCK_STREAM . The Linux implementation does not inherit some socket flags. This may differ from other implementations.
connect()
The Linux man page ( man connect.2 ) documents SOCK_SEQPACKET , while the Solaris OS does not. Linux breaks the association between a connectionless socket and connect() by connecting to an address with sa_family in struct sockaddr set to AF_UNSPEC . This behavior is not documented in the Solaris OS.
send()/recv()
As in the other socket library functions, these behave almost identically between the systems. Linux has some additional flags argument documentation on the man page.
shutdown()
No noticeable difference between the Solaris OS and Linux.
Networking Example
It can be useful to look at an application where some of the differences appear. The tracedump program uses a packet capture library ( libpcap) to read Ethernet packets at the user level. The code to read raw Ethernet is quite different between the Solaris OS and Linux. (libpcap can also be used to examine the differences with other systems, such as FreeBSD, HP-UX, and AIX.) The applicable code in libpcap is at pcap-linux.c and pcap-dlpi.c . The DLPI code is used for Solaris, HP-UX, AIX, and other operating systems. Linux provides a mechanism for reading raw socket packets via the standard socket calls. The Solaris OS uses the getmsg(2) and putmsg(2) calls to receive and send DLPI packets.
The following code demonstrates a way to do user-level packet capture on a network interface in the Solaris OS. This is followed by the analogous code in Linux. This code is a (very greatly) simplified extraction from the libpcap library.
The Solaris code forms DLPI requests and gets DLPI responses to tell the interface that the application wants a copy of all packets arriving at the interface.
The code in Linux is much simpler, as a socket(2) call allows one to specify raw packets. Linux does not use DLPI or STREAMS.
Process/Processor Management
A process on both the Solaris OS and Linux is a running instance of a program. In both the Solaris OS and in Linux (2.6), a process is a container for an address space and one or more threads. Every process in the system has a unique process ID (PID), which remains unique for some time after the process dies. Processes are created using fork(2) and its variants. On Linux, processes (and threads) can also be created using clone(2) , but pthread_create(3) is more portable. On the Solaris OS, the undocumented lwp_create() system call is somewhat analogous to clone(2) .
vfork() performs similarly on both systems. The Solaris OS has fork1() and forkall() . In the case of fork1() , this causes the child process to only have the thread that executed the fork() call; in the case of forkall() , all the threads that were in the parent are replicated in the child. The default fork is fork1() . forkall() must be explicitly used. forkall() does not exist in Linux, (i.e., Linux only supports fork1() semantics).
The ps -elfL command can be used on both the Solaris OS and Linux to see the threads in a process. Both systems report the number of LWPs and the lwpid for each thread in the process. Note that an lwpid is unique across processes in Linux. In the Solaris OS, the lwpid is unique within the process. In Linux, the process ID of a multithreaded process is actually a thread group ID. The thread group ID is equivalent to the process ID of the main thread. Sending a signal (via kill(1)/kill(2) ) to any lwpid is equivalent to sending the signal to the process. In the Solaris OS, you send the signal to the pid . In both cases, if the default action is taken, the process typically exits and all threads are terminated. See the man page for ps(1) for more details.
Both Linux and the Solaris OS support the notion of binding a process or thread to a processor. Linux allows binding to a set of processors for non-exclusive use of those processors. The Solaris OS allows binding to a set of processors for exclusive use, (that is, CPU fencing), but does not allow binding to a group for non-exclusive use (except via Solaris Zones?). Linux does not have a mechanism for CPU fencing, though implementations can be found on the web (see, for example, the CPUSETS for Linux page on the bullopensource.org site). The Linux system calls that are processor affinity based are sched_setaffinity(2) and sched_getaffinity(2) . The Solaris OS has the following:
- processor_bind(2) to bind/unbind LWPs or processes to a processor
- pset_create(2) to set up a processor set
- pbind(1) and psrset(1) , which are command-line interfaces
For completeness, output of the ps(1) command, first on Linux, then on the Solaris OS, is shown in the section on Threads.
On Linux and the Solaris OS, all forms of the exec system call result in calling execve(2) . The Solaris OS documents all six flavors of exec(2) on the same manual page. The Linux man page exec(3) documents execv , execl , execle , execlp , and execvp . A separate page covers execve(2) .
The /proc file system exists in slightly different variations on Linux and the Solaris OS. On both systems, /proc is a directory containing files whose names are the process IDs of the current active processes on the system. Each PID-named file is in turn a directory. /proc on Linux has various other directories besides processes. Most of these deal with processors, devices, and statistics on the system. On Linux, one looks in /proc to find information about processes, processors, devices, machine architecture, and so on. On the Solaris OS, the same kind of information is typically available by using a command. For instance, prtconf(1) can be used to learn about machine configuration on the Solaris OS. On Linux, this is done largely by looking at files in /proc .
The virtual address space used by processes can be examined using pmap(1) on the Solaris OS, and by catting the /proc/ pid/maps file on Linux, as shown below. See pmap(1) on the Solaris OS and proc(5) on Linux for more details.
For the equivalent on Linux, see Figure 1. Note that Linux shows the full path name to libraries (the output has been edited to only show the library name). To get the full path names to libraries on the Solaris OS, use pldd(1) .
Figure 1: Examining Virtual Address Space Used by Processes in Linux
Threads
Linux and the Solaris OS support POSIX threads, Linux via The Native POSIX Thread Library for Linux (PDF), and the Solaris OS as part of the standard C library. See Multithreaded Programming Guide (PDF), specifically, Chapter 5 Programming with the Solaris Software, for details of threads on the Solaris OS. Also quite good is the white paper Multithreading in the Solaris Operating Environment.
In addition to POSIX threads, the Solaris OS supports «Solaris threads». The threads(5) man page describes the similarities and differences between the POSIX thread library and the Solaris thread library. The implementations are interoperable and can be used with care within the same application. The following is straight from the man page.
Similarities
Most of the functions in the libpthread and libthread libraries have a counterpart in the other corresponding library. POSIX function names, with the exception of the semaphore names, have a «pthread» prefix. Names for similar POSIX and Solaris functions have similar endings. Typically, similar POSIX and Solaris functions have the same number and use of arguments.
Differences
- POSIX threads are more portable.
- POSIX threads establish characteristics for each thread according to configurable attribute objects.
- POSIX pthreads implement thread cancellation.
- POSIX pthreads enforce scheduling algorithms.
- POSIX pthreads allow for clean-up handlers for fork(2) calls.
- Solaris threads can be suspended and continued.
- Solaris threads implement interprocess robust mutex locks.
- Solaris threads implement daemon threads, for whose demise the process does not wait.
The following is a very simple MT program. Very few differences are found in the ways in which multithreaded applications work between the two OSes. Of course, the underlying implementations have several differences.
Use the following to compile and run the program on the Solaris platform:
Using gcc on the Solaris platform gives the same results. On Linux it appears thus:
On Linux, the POSIX thread library needs to be explicitly linked. Note that Solaris 9 and earlier versions also require this. In the Solaris 10 OS, POSIX threads are in the standard C library ( libc.so ). Note also that the Solaris OS assigns thread IDs using a monotonically increasing integer starting at 1. Linux uses the user virtual address of the pthread structure (structure used internally by the thread library).
Visibility to threads is provided on both systems by the ps(1) command, and via the /proc file system. See Figure 2 for the output of the ps(1) command on the Solaris platform and Figure 3 for the output on Linux. You’ll see that, given the same options, the output is very similar between the machines.
Figure 2: Output of ps(1) Command on Solaris Platform
Figure 3: Output of ps(1) Command on Linux
The command shows state, user, PID, parent PID, LWP ID, number of LWPs (for user processes, this is the number of threads), scheduling class, scheduling priority, user virtual size, wait channel, start time, tty, time spent running, and command. Linux does not report ADDR , and the Solaris OS shows the (kernel) virtual address of the proc_t data structure, which the kernel uses to maintain the process. Linux shows WCHAN as a symbol, while the Solaris OS shows it as an address. In the Solaris OS, the WCHAN column is the address of a synchronization variable on which the thread is blocked. On Linux, WCHAN is the routine in which the thread is sleeping. To get the equivalent information in the Solaris OS, use ::threadlist -v inside of mdb -k .
Note that on a machine running a 64-bit kernel (that is, SPARC or AMD64 architecture based), the ADDR and WCHAN fields will display a question mark ( ? ). To see the values for these two fields, use ps -e -o addr,wchan,comm .
More likely, you are interested in what the application threads are doing. For this, use pstack(1) on the process ID of interest. There is a pstack on Linux, but it must be downloaded. Search for it on http://rpmfind.net/linux/RPM/. Note that it only gives the stack backtrace of one thread (the thread ID that is passed to it as an argument). If you want a backtrace of all threads within a process, you need to pass the thread IDs as separate arguments.
Here is an equivalent on Linux. It is interesting that programs like Mozilla and xemacs are stripped on Linux and not stripped on the Solaris OS.
Solaris threads are given a default user stack size of 1MB. For Linux, the default stack size is 2MB (SuSe 9.1).
Synchronization
Both OSes support POSIX synchronization mechanisms, i.e., mutexes, condition variables, reader/writer locks, semaphores, and barriers. The underlying mechanisms rely on mutexes. In Solaris, user-level mutexes are implemented using «adaptive» spin locks. On Linux, the mechanism is the «futex», or fast user level mutex. Both mechanisms avoid going into the kernel in the non-contention case, and should give comparable performance and behavior.
The Solaris user-level adaptive spin mutexes are described in Multithreading in the the Solaris Operating Environment. Linux futexes are described in Futexes Are Tricky (pdf).
The Solaris OS mechanisms lwp_park() and lwp_unpark() , and Linux mechanisms futex_up() and futex_down() , can be used by applications. However, I have not found any source code examples. It is probably best to stick with the POSIX APIs. If you want to compare relative speeds of the POSIX locking mechanisms (as well as performance of various other library routines and system calls), I recommend getting a copy of the libmicro micro benchmark and trying it out on both the Solaris OS and Linux.
Memory Management
Without describing differences in the kernels’ handling of memory, we can say that at user level several different memory allocation (malloc) libraries exist, most of which are available (or can be built) for either OS. A comparison of some of the user-level memory allocators can be found in the Sun Developer Network article A Comparison of Memory Allocators in Multiprocessors. «A Memory Allocator» at http://gee.cs.oswego.edu/dl/html/malloc.html contains a (dated) description of a memory allocator used on Linux. More comments can be found in the source code.
Timers
At application level, the Solaris OS and Linux both offer POSIX timer routines, including timer_create() , timer_delete() , and nanosleep() . The Solaris OS has an additional timer, CLOCK_HIGHRES , that attempts to use an optimal hardware source, and may give close to nanosecond resolution. A CLOCK_HIGH_RES timer may give similar resolution on Linux, but needs to be installed as a kernel patch (see home page for the high resolution timers project at http://high-res-timers.sourceforge.net/ for details). The following is example code that uses the CLOCK_HIGHRES timer to fire on user-specified intervals for a user-specified duration. The interval is specified in nanoseconds, and the duration in seconds. When the program completes, it prints the number of times the timer fired, and the number of times the timer was «overrun». The «overrun» value is a count of the number of timer expirations that occurred between the time a timer fired (causing a signal to be generated), and the time the signal is handled (see timer_getoverrun(3RT) . Running the program real-time with too short an interval may cause the system to hard hang.
And here are some examples of running the compiled code.
Both the Solaris OS and Linux support System V IPC (shared memory, message queues, and semaphores). Both systems also support pipes and the real-time shared memory operations ( shm_open() , shm_unlink() , and so on). Both systems support the tmpfs file system (using memory and swap space for files). The Solaris OS places /tmp , /var/run , and /etc/svc/volatile in tmpfs. Linux uses /dev/shm . Both systems allow other mount points to be added.
Here are the steps for using tmpfs on the Solaris OS; steps for Linux are shown below. Note that «swap» on the Solaris OS uses memory as well as disk (if needed). In other words, files created in /tmp are stored in memory. If memory gets full, the pageout daemon may write data from /tmp to swap space on disk.
And here are the analogous steps on Linux.
It might be interesting to run the libmicro benchmarks mentioned earlier in the article to get some idea of relative performance between the systems.
Signal Handling
The Solaris OS and Linux treat signals similarly. Some signals exist in the Solaris OS and not in Linux, and vice versa. Also, some of the same signals use different signal numbers. Both OSes recommend using sigaction(2) over signal() to catch signals, and the use of sigwait() to handle asynchronous signals in multithreaded applications. The sigwait(3) manual page on Linux has a BUGS section. The Linux signal handling differs from the POSIX standard. POSIX states that an asynchronously delivered signal (a signal sent externally to the process), is handled by any thread that does not have the signal currently blocked. In Linux, asynchronous signals may be sent to specific threads (signals can be sent to the thread ID via kill(1) ). The Solaris OS implements the POSIX standard for this. There is no way to send a signal to a specific thread externally to the process. One can send a signal via kill(1) to the process, not to a specific thread within the process.
Some of the differences are described in «Building Applications with the Linux Standard Base» at http://lsbbook.gforge.freestandards.org/sig-handling.html. Note that this page may not be entirely accurate. For instance, the page says that Linux sets SIGBUS to SIGUNUSED because there is no «bus error» in Linux. However, the Linux man page for mmap(2) documents receiving SIGBUS when accessing a memory range that does not correspond to a valid location in the file that mmap was used with. (The Solaris OS does the same).
On both the Solaris OS and Linux, signals are handled when a non-held, non-ignored signal is found pending for a thread returning from kernel to user mode. On both systems, SIGKILL and SIGSTOP take priority over other signals. Otherwise, on Solaris signals are handled in an undocumented order (lowest signal number first). On Linux, signals are handled in the order they are delivered (again, excepting SIGKILL and SIGSTOP ).
On the Solaris OS, to see the signal settings for a running process, use psig .
As far as I can tell, there is no easy way to do this in Linux, but someone has probably implemented a kernel patch/module to give you the information. Certainly it should be do-able with User Mode Linux.
Conclusions
Generally, if you are developing a POSIX-compliant application on Linux or the Solaris OS, the application should port to the other OS simply by recompilation. Of course, many applications will have parts that are not addressed by POSIX. For instance, device ioctl(2) handling tends to be OS (and, of course, device) specific.
Источник